I keep getting error
Invalid argument supplied for foreach()
when trying to populate select options with the array I've made in Laravel controller. Below is my code. Thanks
Controller :
public function index()
{
$select_options = array(
array(
'name' => 'ALL',
'value' => 'all',
),
array(
'name' => 'Option 1',
'value' => 'option_2',
),
array(
'name' => 'Option 2',
'value' => 'option_2',
),
);
return view('home', [
'select_options' => $select_options,
]);
}
HTML :
@php
$old_business_unit= old('old_select_options', $filters['select_options'] ?? null);
@endphp
<select class="form-control custom-select @error('select_options')is-invalid @enderror" name="select_options">
<option value="">-</option>
@foreach ($select_options as $select_option)
@if ($select_option->value == $old_select_options)
<option value="{{ $select_option->value }}" selected>{{ $select_option->name }}</option>
@else
<option value="{{ $select_option->value }}">{{ $select_option->name }}</option>
@endif
@endforeach
</select>
@error('select_options')
<div class="invalid-feedback">
{{ $message }}
</div>
$select_option
is an array, not an object. $select_option->value
won't work. It will most likely throw the error : " Trying to access property 'value' of non-object. "
The correct notation to access the 'value' key of the $select_option
array is $select_option['value']
.
@foreach ($select_options as $select_option)
@if ($select_option['value'] == $old_select_options)
<option value="{{ $select_option['value'] }}" selected>{{ $select_option['name'] }}</option>
@else
<option value="{{ $select_option['value'] }}">{{ $select_option['name'] }}</option>
@endif
@endforeach
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.