Search code examples
phpforeachlaravel-5.3

A different "Invalid argument supplied for foreach()" issue


OK... So... I've search SO and Google for this error, but all the answers I found where not relevant to my strange situation.

I just installed my first Laravel 5.3 app (worked with 5.2 earlier) to use for as local shopping list/price check app.

Trying to make a form:

ProductController:

$stores = Store::get();
return view('product.add', [
    'stores' => $stores,
]);

add.blade:

<select name="store_id" id="store_id">
@foreach ($stores as $store)
    <option value="{{ $store->id }}">{{ $store->name }} - {{ $store->address }}</option>
@endforeach
</select>

This results in the following error:

ErrorException in FormBuilder.php line 561:
Invalid argument supplied for foreach() (View: E:\wamp\www\shopping\resources\views\product\add.blade.php)

$stores is not empty, because dd($stores) produces a collection with all the stores in my database.

I compared this code and the dd results to other apps of mine that work as expected, all exactly the same. I even tried @forelse.

Is there anything changed in Laravel 5.3 that could influence this? Did I miss anything?


Solution

  • Found the problem guys, thanks to a comment by @bagus-tesa.

    The Formbuilder.php referred to in the error message was of LaravelCollective Form & HTML ("We maintain Laravel components that have been removed from the core framework"), which made me go look at line 561 of that file. There was a foreach statement, which is used to build a select input. This made me realize that I had another select list in my form, so I looked at that.

    {!! Form::select('category_id', null, null, array('class' => 'form-control')) !!}
    

    The second argument should hold an array of options for the list, which is processed by Formbuilder with a foreach loop!

    So... I just spent hours looking at the wrong foreach loop!