Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 921
Josh Avatar asked Jul 28 '13 23:07

Josh


4 Answers

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>
like image 120
Adrian Ortiz Martinez Avatar answered Nov 11 '22 21:11

Adrian Ortiz Martinez


The lists() must be called at last

$client = Client::where('group_id','=', 1)->lists('name','id');
like image 32
Loken Makwana Avatar answered Nov 11 '22 21:11

Loken Makwana


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.

like image 8
Josh Avatar answered Nov 11 '22 20:11

Josh


This would work too

Client::where('group_id','=', 1)->lists('name');
like image 6
Abbas Avatar answered Nov 11 '22 19:11

Abbas