Constraining relationship data with Laravel query builder

By Michael Williams, Published on 05/26/2018

Sometimes when you work with relations in Laravel, a need me arise to add a constraint to the relatioship data. In Laravel terms, this is referred to as Constraining Eager Loads.

Assumming that you have a User and Post Model. One might build a query as such to retrieve active posts for a specific user.

$this->posts->whereStatus('published')->whereUserId($userId)->get();

When loading the User with the Post relationship, we can also get the published posts only by running:

$this->user->with(['posts' => function ($query) { $query->where('status', 'published'); }])->get();

There also may be a time where we only want to return specific columns from a relationship result set. That can be achieved as follows:

$this->user->with(['posts' => function ($query) { $query->select('id', 'title'); }])->get();