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
CodePudding user response:
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.
CodePudding user response:
Try this way
<div >
@foreach ($users as $user)
{{ $user->name }}
@endforeach
</div>
{{ $users->links() }}
Laravel pagination https://laravel.com/docs/9.x/pagination can help you.