Anvil
Anvil - The mobile companion for Laravel Forge. Available now. Download for iOS

Refactoring with Laravel's new whereRelation methods

Prior to this simple PR, we needed verbose closures to do simple queries on relationships. Now it can be done on one line with these simple helpers.

AR
Anthony Rappa
1 min read - 13,986 views -

Prior to this simple PR, we needed verbose closures to do simple queries on relationships. Now it can be done on one line with these simple helpers.

This is how you would currently query the relationship on a model to narrow down your results.

1// Get me all users who have posts that are to be published in the future.
2User::whereHas('posts', function ($query) {
3 $query->where('published_at', '>', now());
4})->get();

With this new PR, we can now refactor and simplify the above to the following:

1User::whereRelation('posts', 'published_at', '>', now())->get();

As you can see, we have collapsed the closure into the parameter list of the whereRelation method.

With this PR, you also have access to orWhereRelation, whereMorphRelation, and orWhereMorphRelation.

It is worth noting that because it uses a where clause under the hood, it would not be possible to use scopes:

1User::whereHas('posts', function ($query) {
2 $query->notPublished();
3})->get();

Or nested where:

1User::whereHas('posts', function ($query) {
2 $query
3 ->whereHas('tags', function ($query) {
4 $query->where('name', 'Laravel');
5 })
6 ->where('published_at', '>', now());
7})->get();

Though you should be able to use nested relations if you don't have any intermediate where clauses:

1User::whereRelation('posts.tags', 'name', 'Laravel')->get();

Read next

What's New in Laravel: 8.58 - 8.68

Are you like me and find it impossible to find the time to keep up with the changes in Laravel on a weekly basis? In this series I'll try to roll them up periodically into one post.

AR
3 min read - 9,225 views -

Mastering Laravel’s data_get(): Read Anything from Arrays, Objects, and Collections

If you’ve ever written a long chain of null checks to fetch a deeply nested value — foo['bar']['baz'] ?? null — you’ll love Laravel’s data_get() helper. It’s a tiny, dependable utility that safely retrieves values from arrays, objects, ArrayAccess implementations, and even nested structures using a simple “dot notation.”

6 min read - 7,874 views -