0

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>

1 Answer 1

3

$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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.