Foreach inside a Form::select in Laravel 4 - laravel-4

I try to walk a variable using the helpers of Laravel but it trhows an error, and when I do the same with html tags it works correctly.
{{ Form::select('categoria', array(
#foreach($enlaceid as $categoria)
$categoria->id => $categoria->nombre {{-- I tryed too with englobing with {{ }}
)) }}
#endforeach
<select name="categoria">
#foreach($enlaceid as $categoria)
<option value= " {{ $categoria->id }} "> {{$categoria->nombre}} </option>
#endforeach
</select>

Use the lists() method and pass that to your Form::select() method. Like so:
$categories = Category::lists('name', 'id');
In your view:
{{ Form::select('category_id', $categories) }}

for you want to use foreach laravelcollective in laravel 5.2 or above, you can use same as #garethDaine but above laravel 5.2, you using pluck() instead lists() because lists() function was depracated in laravel 5.2.
so in the examples is:
$banks = Bank::pluck('name', 'id');
instead
$banks = Bank::lists('name', 'id');
then in your view form:
{!! Form::select('bank_id', $banks, null, ['class' => 'form-control']) !!}
Note: 1st array in you pluck() will be name display on you <option> and second will be value="1" as example.

The answer by Gareth Daine edited by Drew Hammond worked for me, with a slight edit
My Controller
$category = Category::all();
My View
{!! Form::select('category_id', $categories->pluck('name', 'id')) !!}

In case you want to add a default value also to your options you need to do this:
$categories = Category::lists('name', 'id')->toArray();
In your view:
{{ Form::select('category_id', array('0' => 'Default') + $categories) }}

Related

Return Logged User's Posts Into laravelcollective/html Select Dropdown Menu Within a Form

I am trying to pass only the posts created by the logged in user into a laravelcollective/html select drop down menu within a form.
In my code I have two examples. Using the variable example shows how I can get the dropdown select menu to show all results from the posts table. Using the variable posts in a foreach loop shows how I can return just the posts created by the logged user, but not in a select menu.
I need to have the dropdown menu function as in the form using example but displaying results of the foreach posts loop.
Controller
public function createPost()
{
$example = Post::pluck('title', 'id')->all();
$posts = Posts::all();
return view('post.create', compact('posts', 'example'));
}
Example View
<div class="form-group">
{!! Form::label('example', 'Posts:') !!}
{!! Form::select('example', ['' => 'Select'] + $example, null) !!}
</div>
Foreach Loop Posts View
#foreach($posts as $post)
#if(Auth::user()->id == $post->user_id)
{{ $post->title }} <br>
#endif
#endforeach
try $posts = Posts::where('user_id',\Auth::id())->get()->pluck('title','');. It will return only posts of logged in user.
{{ Form::select('example', $posts) }}
You are using select box wrong.
#foreach($posts as $post)
#if(Auth::user()->id == $post->user_id)
{{ $post->title }} <br>
#endif
#endforeach
I would update your controller to only return posts by the user rather than rely on the foreach check if Auth::user()->id == $post->user_id
public function createPost()
{
$posts = Posts::where('user_id', auth()->user()->id)->get();
return view('post.create', compact('posts'));
}
As a side note, your method should probably just be create() to keep inline with the standard CRUD.
Then in your blade,
<div class="form-group">
{!! Form::label('post', 'Posts:') !!}
{!! Form::select('post', ['' => 'Select'] + $posts, null) !!}
</div>

how to display dynamic value without using foreach loop in laravel

How to print these type of data in laravel.I am trying to create dynamic menu and these type of problem occurs.Code is like this. my code is like this.
In view composer.
public function compose(View $view)
{
$menus = $this->menu->getDynamicMenus();
$user_role = $this->role->lists('name', 'id');
//dd($user_role);
$view->with('user_role', $user_role)->with('menus', $menus);
}
menurepository code.
public function getDynamicMenus()
{
$user = $this->auth->user();
$roles = $user->roles;
// dd($roles);
$menus = [];
foreach ($roles as $role) {
//dd($role);
foreach ($role->menus as $menu) {
if ($menu["parent_id"] > 0) {
$menus[$menu["parent_id"]][$menu["id"]] = $menu->toArray();
} else {
$menus[$menu["id"]] = $menu->toArray();
}
}
}
// dd($menus);
return $menus;
}
and i print in frontend like.
#foreach($menus as $menu)
{{-- {!! Form::open() !!}
{!! Form::select('menus',$menus) !!}
{!! Form::close() !!}--}}
{{--{!! $menuitem->menu_name !!}--}}
{!! $menu->menu_url !!}
#endforeach
and it shows problem:
Trying to get property of non-object (View: E:\xampp\htdocs\basicwc\resources\views\layouts\partials\sidebar.blade.php) (View: E:\xampp\htdocs\basicwc\resources\views\layouts\partials\sidebar.blade.php) (View: E:\xampp\htdocs\basicwc\resources\views\layouts\partials\sidebar.blade.php)
as menu are getting in array like in image.
any help??
i tried to do like:
{!! menu($menus) !!}
but it says undefined problem.
I added another menu and it's structure is like this:
Access it like an array:
#foreach($menus as $menu)
...
{{ $menu['menu_name'] }}
{{ $menu['menu_url'] }}
#endforeach

Foreach inside a Form::select in Laravel 5.2 + default value

So basicaly I have this select:
<select name="models" id="models" class="form-control">
<option value="0">Select a model</option>
#foreach ($models as $model)
<option value="{$model->id}">{$model->name}</option>
#endforeach
</select>
I fetch my models like this:
$models = Model::all();
And I want to transform this into a {!! Form::select() !!} so this is what I did until now :
{!! Form::select('models', $models)) !!}
and I fetch them like this:
$models= Model::lists('name', 'id');
It is almost perfect, what is missing is the default value. I How can I add that also to the options fetched from my database?
I finally found a solution that works for this case:
$models= Model::lists('name', 'id')->toArray();
{!! Form::select('models', array('' => 'Select a model') + $models) !!}
Pass it as a third argument, Eg,
{{ Form::select('number', [0, 1, 2], 2) }}
Ref: http://laravel-recipes.com/recipes/163/creating-a-select-box-field

Laravel pre-filling multiple forms if validation failed

One of the coolest Laravel feature is, Laravel pre-filled the form fields if validation error occurred. However, if a page contain more than one form, and form fields have same name, Laravel pre-filling all forms fields.
For example:
I have a page where i have two forms to create new users or whatever.
<h1>Create user1</h2>
{{ Form::open(array('url' => 'foo/bar')) }}
{{ Form::text('name', null) }}
{{ Form::email('email', null) }}
{{ Form::close() }}
</h1>Create user2</h1>
{{ Form::open(array('url' => 'foo/bar')) }}
{{ Form::text('name', null) }}
{{ Form::email('email', null) }}
{{ Form::close() }}
Controller
class UsersController extends BaseController
{
public function store()
{
$rules = [
'name' => 'required',
'email' => 'required'
];
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
return Redirect::back()->withInput()->withErrors($validation);
}
}
}
As i didn't fill up the email, Laravel will throw validation error and pre-filling the forms as following:
How to tell Laravel that do not fill-up the second form?
There's no Laravel way of doing this, but you can use HTML basic form arrays to make it work. You need to understand that you have to identify your forms and fields so Laravel knows exactly where the data came from and where to send it back to. If all your fields have the same name how could it possibly know?
This is a proof of concept that will work straight from your routes.php file.
As I did it all and tested here before posting the answer I used Route::get() and Route::post(), to not have to create a controller and a view just to test something I will not use. While developing this you will have to put this logic in a controller and in a view, where I think they are alredy in.
To test it the way it is, you just have to point your browser to the following routes:
http://yourserver/form
and when you push a button it will automatically POST tho the route:
http://yourserver/post
I'm basically giving all forms a number and giving the buttons the number that we will usin in Laravel to get the form data and validate it.
Route::get('form', function()
{
return Form::open(array('url' => URL::to('post'))).
Form::text('form[1][name]', null).
Form::email('form[1][email]', null).
'<button type="submit" name="button" value="1">submit</button>'.
Form::close().
Form::open(array('url' => URL::to('post'))).
Form::text('form[2][name]', null).
Form::email('form[2][email]', null).
'<button type="submit" name="button" value="2">submit</button>'.
Form::close();
});
And here we get the data, select the form and pass all of it to the validator:
Route::post('post', function()
{
$input = Input::all();
$rules = [
'name' => 'required',
'email' => 'required'
];
$validation = Validator::make($input['form'][$input['button']], $rules);
return Redirect::back()->withInput();
});
This is how you use it in a Blade view, now using 3 forms instead of 2 and you can have as many forms as you need:
<h1>Create user1</h2>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[1][name]', null) }}
{{ Form::email('form[1][email]', null) }}
<button type="submit" name="button" value="1">submit</button>
{{ Form::close() }}
</h1>Create user2</h1>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[2][name]', null) }}
{{ Form::email('form[2][email]', null) }}
<button type="submit" name="button" value="2">submit</button>
{{ Form::close() }}
</h1>Create user3</h1>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[3][name]', null) }}
{{ Form::email('form[3][email]', null) }}
<button type="submit" name="button" value="3">submit</button>
{{ Form::close() }}
And you can even use a loop to create 100 forms in blade:
#for ($i=1; $i <= 100; $i++)
User {{$i}}
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text("form[$i][name]", null) }}
{{ Form::email("form[$i][email]", null) }}
<button type="submit" name="button" value="{{$i}}">submit</button>
{{ Form::close() }}
#endfor
Use old input with $request->flash().
https://laravel.com/docs/5.2/requests#old-input

Laravel 4 blade drop-down list class attribute

Laravel blade drop down list class attribute not working.
I cannot find any reference to class or assigning attributes to select / drop-down lists in the documentation.
http://www.laravel.com/docs/html#drop-down-lists
Examples tried:
{{ Form::select('product_id', $productList, array('class'=>'form-control')) }}
{{ Form::select('product_id', $productList, $attributes = array('class'=>'form-control')) }}
Both return the same html but without the class attribute:
<select id="product_id" name="product_id">
... Option Stuff ...
</select>
{{ Form::select('product_id', $productList, null, array('class' => 'form-control')) }}
The third parameter is the key of the currently selected option. Defaults to null.
First get and create list in Controller for example:
$username_lists = Users::lists('username','id');
pass data to view by:
return View::make('layouts.customers')
->with('username_lists', $username_lists);
now get in view:
{{ Form::select('username_lists', $username_lists, null, array('class' => 'form-control')) }}

Resources