Ohidul Islam
Ohidul Islam

Reputation: 107

Laravel Eloquent eager loading not working

In my blog application there users can post articles and comments on there. When I go to any user profile http://eloquent-laravel.app/user/Name then I want to eagerly loaded all articles and comments of that certain user. Here's my code but it's not eagerly loading all articles and comments.

$user = \App\User::with(['articles', 'comments'])->where('name', $name)->first(); 
return view('articles.user', compact('user'));

User Model's code

public function articles() 
{
    return $this->hasMany(Article::class);
}

public function comments() 
{
    return $this->hasManyThrough(Comment::class, Article::class, 'user_id', 'article_id');
}

How can I eagerly loaded these articles and comments? But if i remove the where clause then eager loading is working. But I do need to get a certain user with all articles and comments eagerly loaded. Thanks

Upvotes: 1

Views: 2346

Answers (2)

Riasat Raihan Riasat
Riasat Raihan Riasat

Reputation: 39

Okk try this.. in your Article model add

    public function comments() 
{
    return $this->hasMany(Comment::class);
}  

now from your controller or repository add

 $user = \App\User::with(['articles.comments' => function ($query)use($userId) {
        $query->where('user_id',$userId);
}])->where('name', $name)->get(); 

here you will get a particular user's all articles along with his comments only

in another situation(like you want all the comments and posts of a user) you can do this : add this in User Model

public function comments() 
{
    return $this->hasMany(Comment::class);
} 

and then try

$user = \App\User::where('name', $name)->with(['articles', 'comments'])->get();

Upvotes: 3

AndyCola
AndyCola

Reputation: 92

try this :

$user = \App\User::where('name', $name)->with(['articles', 'comments'])->first();

Upvotes: 1

Related Questions