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
3
Answers
The reason is found, the news cannot get its user because he was deleted from the database
Try this way
Laravel pagination
https://laravel.com/docs/9.x/pagination can help you.
answer to the original question:
you have to pass the variable to the included blade file:
answer to the updated question:
try to eager load the relationship (more efficient):
or to load the query every time:
It should work if your foreign key in the
news
table is calleduser_id
. Otherwise you have to explicitly specify your foreign key and local key in your model relationships.