简体   繁体   English

Laravel 用数组填充选择选项

[英]Laravel populate select options with array

I keep getting error我不断收到错误

Invalid argument supplied for foreach()为 foreach() 提供的参数无效

when trying to populate select options with the array I've made in Laravel controller.尝试使用我在 Laravel 控制器中创建的数组填充选择选项时。 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 : 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是一个数组,而不是一个对象。 $select_option->value won't work. $select_option->value不起作用。 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'] .访问$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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM