vinc lre
vinc lre

Reputation: 15

Retrieve data with relations in laravel

I would like to display the name of each entity in my table but it returns me

Property [name] does not exist on this collection instance.

My Controller

$users = User::with('pearls')->latest()->get();

the index.blade.php

<thead>
<tr>
    <th scope="col">SL No</th>
    <th scope="col">Name</th>
    <th scope="col">Email</th>
    @foreach($users as $user)
        <th>{{ $user->pearls->name}}</th>
    @endforeach
    <th scope="col">Actions</th>
</tr>
</thead>

Upvotes: 1

Views: 53

Answers (2)

Red Devil
Red Devil

Reputation: 149

The issue is this line: {{ $user->pearls->name}} in your blade.php

For hasMany relations you cant retrieve data like this. Any relationship that has Many in it's name, example: hasMany or belongsToMany will always return a collection object.

Try dd($users->pearls), it'll return a collection of data. You are trying to call the property name on a collection object, not from a singe model.

When you're using get() method you will get a collection. In this case you need to iterate over it to get properties.

@foreach ($user->pearls as $pearl)
    {{ $pearl->name}}
@endforeach

By using its index you will get one of the object property

@foreach($users as $user)
    <th>{{ $user->pearls[0]->name}}</th>
@endforeach

Or you can use the first() method instead of get() method in your query , so you can easily call the object property like {{ $user->pearls->name}} ,also you need to use one to one relation like hasOne.

Upvotes: 0

Hadi Ahmadi
Hadi Ahmadi

Reputation: 579

Because pearls is a collection, not object! I think you've performed a one-to-many relationship between user and pearl, so, you should use foreach for pearls too:

foreach ($user->pearls as $pearl){
  echo $pearl->name;
}

Upvotes: 3

Related Questions