Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

The whereRelation (A better version of whereHas) method in Laravel 8.x

Checking the existence of relationships and fetching model records is quite easy in Laravel.

for instance, let’s say, you want to retrieve all books which at least have one review, you can do it like so.

use App\Models\Book;

$books = Book::has('reviews')->get();

The existing whereHas method

Now, if you want to go deeper with this, for example, if you only want to retrieve the books which have more than 3 stars, you can use the whereHas method like so.

use App\Models\Book;
use Illuminate\Database\Eloquent\Builder;

$books = Book::whereHas('reviews', function (Builder $query) {
    $query->where('stars', '>', 3);
})->get();

This is all nice but in the recent PR, an alternate method is added which does the same but with better developer experience.

The new whereRelation method

As I mentioned earlier, this PR for Laravel 8.x introduced a method called whereRelation which is essentially the whereHas method that offers better readability and less code complexity by omitting the closure altogether.

Here’s how the previous example can be written using whereRelation.

use App\Models\Book;

$books = Book::whereRelation('reviews', 'stars', '>=', 3)->get();

As you can tell, this method makes the query more readable without the need of passing a closure to it.

The PR also adds few more methods such as the orWhereRelation(), whereMorphRelation() and orWhereMorphRelation() for morph relations that works works the similar way as the whereRelation() method.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?