frosty frosty - 1 month ago 7
PHP Question

Laravel "nested" with()

I have 3 models:

Article
,
Comment
,
Reaction
.

Each article has many comments, and each comment has many reactions:

App\Article:

class Article extends Model
{
public function comments() {
return $this->hasMany('App\Comment');
}
}


App\Comment:

class Comment extends Model
{
public function article() {
return $this->belongsTo('App\Article');
}

public function reactions() {
return $this->hasMany('App\Reactions');
}
}


App\Reaction:

class Reaction extends Model
{
public function comment() {
return $this->belongsTo('App\Comment');
}
}


In my
ArticleController@index
I want to fetch comments and their reactions:

ArticleController:

public function index()
{
$articles = Article::with('comments')
->select('articles.*')
->leftjoin('comments', 'comments.article_id', '=', 'articles.id')
->get();

return view('wiki')->withArticles($articles);
}


I can loop through the comments (
$article->comments
), however I'm not sure how to do a
with('reactions')
for the comments? i.e.,

@foreach($article->comments as $comment)
@foreach($comment->reactions)
// something like this...
@endforeach
@endforeach

Answer

you can do Nested Eager Loading

$article = Article::with('comments.reactions')
                ->leftjoin('comments', 'comments.article_id', '=', 'articles.id')
                ->select('articles.*')
                ->get();