2017-08-15 45 views
0

我正在尝试创建收藏并将其传递给刀片。我的PHP代码看起来象Laravel - 此收藏实例上不存在属性[名称]

$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 

但是我得到这个错误:

Property [name] does not exist on this collection instance

任何想法? 感谢

+0

恩,先尝试'dd($ people_col)',看看它是怎么样的。 –

回答

1

尝试访问的属性名是这样的:$people['name']

@foreach ($people_col as $people) 
     <tr> 
      <td>{{ $people['name'] }}</td> 
      <td>{{ $people['id'] }}</td>    
     </tr> 
@endforeach 
1

你创建你应该创建对象的集合,而不是集合的集合。

根据您目前的执行情况,你应该能够得到使用或使用收集{{ $people->get('name') }}

get方法如果您创建类似下面对象的集合数组访问方法{{ $people['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 
相关问题