Home / Snippets / Querying with whereRelation in Laravel
Querying with whereRelation in Laravel cover

Querying with whereRelation in Laravel

1.3K

3 years ago

0 comments

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();
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this