Laravel: how to populate a blade SELECT with values from a where statement

回眸只為那壹抹淺笑 提交于 2019-12-20 19:41:14

问题


I understand you can send values to a select statement like this:

Controller:

$client = Client::lists('name', 'id');
return View::make('index', compact('client'));

And populate this in my view like so:

View:

{{ Form::select('client_id', $client, Input::old('client_id')) }}

But how do I populate only records from Clients where group_id = 1 for example.

I tried:

$client = Client::lists('name', 'id')->where('group_id', 1)->get();

and

$client = Client::lists('name', 'id')->where('group_id','=', 1)->get();

But it doesn't seem to work like that and gives me the error "Call to a member function where() on a non-object"

Any ideas on how to make it work?


回答1:


Controller:

$client = Client::where('group_id', 1)->pluck('name', 'id');

View:

{!! Form::select('client_id', $client, Input::old('client_id'), ['class'=> 'form-control'])  !!}

Result:

<select id="client_id" class="form-control" name="client_id">
  <option value="1">John</option>
  <option value="2">Karen</option>
</select>



回答2:


The lists() must be called at last

$client = Client::where('group_id','=', 1)->lists('name','id');



回答3:


I found an answer that worked for me:

Use fluent instead of eloquent, which will look something like this:

$client = DB::table('clients')->where('group_id', 1)->lists('name');
return View::make('index', compact('client'));

Then in your view just call it inside blade form tags like this:

{{ Form::select('client_id', $client, Input::old('client_id')) }}

@KyleK, thanks for trying to help.




回答4:


This would work too

Client::where('group_id','=', 1)->lists('name');



回答5:


Not sure if this is a typo or not, but you're not retrieiving properly,

This line should be...

    $client = Client::lists('name', 'id')->where('group_id','=', 1)->get();

Also....

Sometimes when populating lists, you will get models, and its easy to pass them, but sometimes u get arrays (fluent, raw etc) , and in those cases you have to access manually, and build the form with HTML because you have to access it differently.




回答6:


If you prefer to use Laravel's query builder (e.g. for performance reasons):

$clients = DB::table('clients')->get()->pluck('name', 'id')->toArray();
return view('index', compact('clients'));

or, with a select to pull only what's needed:

$clients = DB::table('clients')->select('name', 'id')->get()->pluck('name', 'id')->toArray();
return view('index', compact('clients'));

In your view:

{!! Form::label('client_id', 'Client') !!}
{!! Form::select('client_id', $clients, old('client_id')) !!}


来源:https://stackoverflow.com/questions/17913923/laravel-how-to-populate-a-blade-select-with-values-from-a-where-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!