Laravel: how to populate a blade SELECT with value

2019-03-26 00:28发布

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?

6条回答
再贱就再见
2楼-- · 2019-03-26 01:00

The lists() must be called at last

$client = Client::where('group_id','=', 1)->lists('name','id');
查看更多
疯言疯语
3楼-- · 2019-03-26 01:03

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.

查看更多
Viruses.
4楼-- · 2019-03-26 01:07

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.

查看更多
时光不老,我们不散
5楼-- · 2019-03-26 01:12

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>
查看更多
老娘就宠你
6楼-- · 2019-03-26 01:20

This would work too

Client::where('group_id','=', 1)->lists('name');
查看更多
smile是对你的礼貌
7楼-- · 2019-03-26 01:20

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')) !!}
查看更多
登录 后发表回答