skip to Main Content

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


  1. Chosen as BEST ANSWER

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


  2. 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.

    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search