简体   繁体   English

如何在控制器中通过刀片传递变量(laravel)

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

I'm trying to foreach in a php variable with blade . 我正在尝试使用blade在php变量中进行foreach I'm passing my variable to my view trought my controller but the view return me Undefined variable . 我将变量传递给我的视图使控制器变了,但是视图返回了我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

Edit: As I cant delete, as the OP has accepted the answer, its now just speculative information based upon the docs. 编辑:由于我不能删除,因为OP已经接受了答案,它现在只是基于文档的推测性信息。 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 https://github.com/laravel/framework/blob/v5.5.28/src/Illuminate/View/View.php#L177-L186

Thanks to @patricus for pointing this out: 感谢@patricus指出这一点:

While the docs may not show that it is supported, you can pass an array in the with() method. 尽管文档可能未显示它受支持,但是您可以在with()方法中传递一个数组。 If you do, it is array_merged into the current data set. 如果这样做,它将被array_merged到当前数据集中。


Original Answer: 原始答案:

From the docs, https://laravel.com/docs/5.5/views#passing-data-to-views 从文档中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; ?> 在视图内部,然后可以使用其对应的键访问每个值,例如<?php echo $key; ?> <?php echo $key; ?> . <?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: 除了将完整的数据数组传递给视图帮助器功能之外,您还可以使用with方法将单个数据段添加到视图中:

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

So according to the docs, with may not support passing a single array, so you should change: 因此,根据文档, with可能不支持通过单一的阵列,所以你应该改变:

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
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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