Monday, May 22, 2017

Eager Loading Multiple Associations In Laravel With A Condition On One Association

I've been trying to eager load a Forum model, but I also need a all the boards for that forum, as well as the most recent thread and the user that created that thread for each board. After extensive research, this has been my approach:

public function show($forum)
{

    $forumCol = Forum::with([
        'boards' => function($query) {
            return $query->with(['threads' => function($query) {
                 return $query->with('user')->latest()->first();
            }])->get();
        }
    ])->where('id', $forum)->first();

    return view('forum.forum', ['forum' => $forumCol]);
}

Yet no matter how many different variants of what I put above I try, I can't load neither the thread nor the user. When dd'ing the page with the $forum variable. I get a collection with the forum, and the associated boards, yet I can't load the Thread (hence the user as well).

Is my syntax incorrect for this eager load? I've been working on this for a couple hours and any help would be much appreciated.

Thanks



via Dastur

Advertisement