Laravel Querying on relationships


Example

Eloquent also lets you query on defined relationships, as show below:

User::whereHas('articles', function (Builder $query) {
    $query->where('published', '!=', true);
})->get();

This requires that your relationship method name is articles in this case. The argument passed into the closure is the Query Builder for the related model, so you can use any queries here that you can elsewhere.

Eager Loading

Suppose User model has a relationship with Article model and you want to eager load the related articles. This means the articles of the user will be loaded while retrieving user.

articles is the relationship name (method) in User model.

User::with('articles')->get();

if you have multiple relationship. for example articles and posts.

User::with('articles','posts')->get();

and to select nested relationships

User::with('posts.comments')->get();

Call more than one nested relationship

User::with('posts.comments.likes')->get()