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

1211 views

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.
<?php

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

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.
<?php

Article::query()
  ->whereHas('comments', fn ($query) => $query->where('article_id', 1))
  ->get();

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.
<?php

Article::query()
  ->whereHas('comments', 'article_id', 1)
  ->get();

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

)