Laravel / Blade dropdown - for more than one field
I am trying to use blade to display dropdown from table data. The problem I am having is that I want to display the results of two fields in a concatenated table, not just one.
So, I want to do something like:
<select id="agreement_type" name="agreement_type">
<option value="1">Agreement Field 1 - Agreement Field 2</option>
<option value="2">Agreement Field 1 - Agreement Field 2</option>
<option value="4">Agreement Field 1 - Agreement Field 2</option>
</select>
At the moment my controller looks like this:
$agreements = Agreement::lists('agreement_type','id');
return View::make('client_agreements.create')
->with('agreements', $agreements);
Now my blade view looks like this:
<div class="form-group">
{{ Form::label('agreement_type', 'Agreement type') }}
{{ Form::select('agreement_type', $agreements) }}
</div>
I tried to change the view and controller differently to get the desired result. But can't get it to work.
I want to display agreement_type
and level
and set id
as a value so that I try;
$agreements = Agreement::lists('agreement_type'.'level','id');
But it just displays level
as meaning and ignores it completely id
.
source to share
This is the easiest method. Just use a loop foreach
to construct an array of parameters:
$agreements = Agreement::all();
$agreementOptions = array();
foreach($agreements as $agreement){
$agreementOptions[$agreement->id] = $agreement->agreement_type.' '.$agreement->level;
}
return View::make('client_agreements.create')
->with('agreements', $agreementOptions);
However, you can also define an attribute of an attribute in your model. You can use this to create new properties that can be accessed normally, but you can run logic to create them (like combining with attributes)
public function getSelectOptionAttribute(){
return $this->attributes['agreement_type'].' '.$this->attributes['level'];
}
And then you can use lists
:
$agreements = Agreement::all()->lists('select_option', 'id');
(Laravel converts SelectOption
(studly case) from method name to select_option
(snake case) for attribute, so don't confuse it)
source to share