Created
September 7, 2021 04:36
-
-
Save Merazsohel/4d58334efcda3a2032f8cf377e92e9d8 to your computer and use it in GitHub Desktop.
Laravel Where Relation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get me all users who have posts that are to be published in the future. | |
User::whereHas('posts', function ($query) { | |
$query->where('published_at', '>', now()); | |
})->get(); | |
we can now refactor and simplify the above to the following: | |
User::whereRelation('posts', 'published_at', '>', now())->get(); | |
As you can see, we have collapsed the closure into the parameter list of the whereRelation method. | |
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: | |
User::whereHas('posts', function ($query) { | |
$query->notPublished(); | |
})->get(); | |
Or nested where: | |
User::whereHas('posts', function ($query) { | |
$query | |
->whereHas('tags', function ($query) { | |
$query->where('name', 'Laravel'); | |
}) | |
->where('published_at', '>', now()); | |
})->get(); | |
Though you should be able to use nested relations if you don't have any intermediate where clauses: | |
User::whereRelation('posts.tags', 'name', 'Laravel')->get(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment