AlexPham
AlexPham

Reputation: 321

Laravel - Property [name] does not exist on this collection instance

I am trying to create a Collection and pass it to blade. My PHP code look like this

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

In my blade I loop through people_col to get properties of items:

 @foreach ($people_col as $people)
        <tr> 
            <td>{{ $people->name }}</td>
            <td>{{ $people->id }}</td>               
        </tr>
 @endforeach

However I got this error:

Property [name] does not exist on this collection instance

Any idea? Thanks

Upvotes: 1

Views: 1423

Answers (2)

chanafdo
chanafdo

Reputation: 5124

You are creating a collection of collections where you should have created a collection of objects instead.

With your current implementation you should be able to get the values using array access method {{ $people['name'] }} or using get method on collection {{ $people->get('name') }}

If you created a collection of objects like below and return it instead of what you are doing now

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

Then in your view you should be able to access people object like you have done in your code.

@foreach ($people_col as $people)
    <tr> 
        <td>{{ $people->name }}</td>
        <td>{{ $people->id }}</td>               
    </tr>
@endforeach

Upvotes: 2

Miller
Miller

Reputation: 87

Try to access to the property name this way: $people['name']

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

Upvotes: 1

Related Questions