Laravel - 此集合实例上不存在Property [name]

时间:2017-08-15 03:16:11

标签: laravel-5

我正在尝试创建一个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]

有什么想法吗? 感谢

2 个答案:

答案 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