我正在尝试创建一个Collection并将其传递给blade。我的PHP代码看起来像这样
$collection1 = collect(['name' => 'Alex', 'id' => '1']);
$collection2 = collect(['name' => 'John', 'id' => '2']);
$collection3 = collect(['name' => 'Andy', 'id' => '3']);
$people_col = new Collection();
$people_col->push($collection1);
$people_col->push($collection2);
$people_col->push($collection3);
return view('test',[
'people_col' => $people_col
]);
在我的刀片中,我循环浏览people_col
以获取项目的属性:
@foreach ($people_col as $people)
<tr>
<td>{{ $people->name }}</td>
<td>{{ $people->id }}</td>
</tr>
@endforeach
但是我收到了这个错误:
此集合实例上不存在属性[name]
有什么想法吗? 感谢
答案 0 :(得分:2)
您正在创建一个集合集合,您应该在其中创建一组对象。
使用您当前的实现,您应该能够使用数组访问方法{{ $people['name'] }}
或使用get
方法获取值{{ $people->get('name') }}
如果你创建了一个像下面这样的对象集合并返回它而不是你现在正在做的事情
$people_col = collect([
(object) ['name' => 'Alex', 'id' => '1'],
(object) ['name' => 'John', 'id' => '2'],
(object) ['name' => 'Andy', 'id' => '3']
]);
return view('test', [
'people_col' => $people_col
]);
然后在您的视图中,您应该能够像在代码中一样访问人物对象。
@foreach ($people_col as $people)
<tr>
<td>{{ $people->name }}</td>
<td>{{ $people->id }}</td>
</tr>
@endforeach
答案 1 :(得分:1)
尝试以这种方式访问媒体名称:$people['name']
@foreach ($people_col as $people)
<tr>
<td>{{ $people['name'] }}</td>
<td>{{ $people['id'] }}</td>
</tr>
@endforeach