[英]Laravel populate select options with array
我不斷收到錯誤
為 foreach() 提供的參數無效
嘗試使用我在 Laravel 控制器中創建的數組填充選擇選項時。 下面是我的代碼。 謝謝
控制器 :
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
是一個數組,而不是一個對象。 $select_option->value
不起作用。 它很可能會拋出錯誤:“試圖訪問非對象的屬性‘值’。 ”
訪問$select_option
數組的 'value' 鍵的正確符號是$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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.