Posts Learn Components new Snippets new Categories Tags 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

96 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();
new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻