Posts Learn Components Snippets Categories Tags Tools About

Querying with whereRelation in Laravel

Learn how to query with the new whereRelation in Laravel to simplify your model relationship condition logic

Created on Sep 17, 2021


Laravel has a new "whereRelation" method that allows you to query the relation directly without passing much data like the previous "whereHas" method.

Below are the code examples of how to simplify querying a modal relationship that has a specific condition.

Laravel whereHas Method

Using "whereHas" function can allow you to query a model to check the condition of the relationship model and it works by passing the "relation" as the first param and closure as the second param to check the condition.

  ->whereHas('comments', function ($query) {
    $query->where('article_id', 1);

Laravel whereHas Method with Anonymous Function

With PHP 7.4 you can make use of the arrow function to simplify the closure definition. This makes the closure into a one-liner and can be considered to be more straightforward.

  ->whereHas('comments', fn ($query) => $query->where('article_id', 1))

Laravel whereRelation Method

With the new "whereRelation" method now you can pass in the foreign key of the relationship into the second parameter and the "id" as the third parameter.

  ->whereHas('comments', 'article_id', 1)

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Querying with whereRelation in Laravel


PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Sponsors 👑

+ Add Yours