MathieuAuclair
MathieuAuclair

Reputation: 1327

How to foreach with blade in a controller passed variable (laravel)

I'm trying to foreach in a php variable with blade. I'm passing my variable to my view trought my controller but the view return me Undefined variable. I would like to know what's the right way to do this.

My Controller:

return view('pages.menu')->with([
    'someList' => $this->someList
]);

My View:

@foreach($someList as $item)
    @include('item.line', [
    'itemName' => $item->name,
    'itemValue' => $item->itemValue
])
@endforeach

Upvotes: 1

Views: 2095

Answers (1)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

Edit: As I cant delete, as the OP has accepted the answer, its now just speculative information based upon the docs. What your doing should work according to the source:

https://github.com/laravel/framework/blob/v5.5.28/src/Illuminate/View/View.php#L177-L186

Thanks to @patricus for pointing this out:

While the docs may not show that it is supported, you can pass an array in the with() method. If you do, it is array_merged into the current data set.


Original Answer:

From the docs, https://laravel.com/docs/5.5/views#passing-data-to-views

You may pass an array of data to views:

return view('greetings', ['name' => 'Victoria']);

When passing information in this manner, the data should be an array with key / value pairs. Inside your view, you can then access each value using its corresponding key, such as <?php echo $key; ?>.

As an alternative to passing a complete array of data to the view helper function, you may use the with method to add individual pieces of data to the view:

return view('greeting')->with('name', 'Victoria');

So according to the docs, with may not support passing a single array, so you should change:

return view('pages.menu')->with([
    'someList' => $this->someList
]);

To:

return view('pages.menu')->with('someList', $this->someList);

or:

return view('pages.menu', [
    'someList' => $this->someList
]);

Upvotes: 2

Related Questions