Yurei
Yurei

Reputation: 19

laravel relationship method working incorect

Method in model User

public function news()
{
    return $this->hasMany(News::class);
}

Method in model News

public function user()     
{    
    return $this->belongsTo(User::class);
};

Work

$user=User::all();
dd($user[0]->news->user->name);

Not work

$news=News::all();
dd($news[0]->user->name);

But array objects 'news' i getted

Upvotes: 0

Views: 50

Answers (3)

Yurei
Yurei

Reputation: 19

The reason is found, the news cannot get its user because he was deleted from the database

Upvotes: 0

Valentino
Valentino

Reputation: 542

answer to the original question:

you have to pass the variable to the included blade file:

@foreach($news as $newsCard)
    @include('includes.news.card', ['newsCard' => $newsCard])
@endforeach
{{$news->links()}}

answer to the updated question:

try to eager load the relationship (more efficient):

$news=News::with('user')->all();

or to load the query every time:

$news[0]->user()->name

It should work if your foreign key in the news table is called user_id. Otherwise you have to explicitly specify your foreign key and local key in your model relationships.

Upvotes: 1

Alfredo Osorio
Alfredo Osorio

Reputation: 116

Try this way

<div class="container">
@foreach ($users as $user)
    {{ $user->name }}
@endforeach
</div>
 
{{ $users->links() }}

Laravel pagination https://laravel.com/docs/9.x/pagination can help you.

Upvotes: 0

Related Questions