Laravel filtering relationship data using whereHas and whereDoesn'tHave
In Laravel, filtering relationship data is a common task when working with Eloquent ORM. Laravel provides several methods to filter relationship data, and two of the most commonly used methods are whereHas
and whereDoesn'tHave
queries. In this answer, we will discuss these methods in detail with examples.
First, let's understand the context of these methods. Suppose we have two tables, users
and posts
. A user can have many posts, and each post belongs to a user. We can define these relationships in Laravel as follows:
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Now, let's see how we can use whereHas
and whereDoesn'tHave
queries to filter relationship data.
whereHas
The whereHas
method is used to filter records based on a relationship that exists. For example, let's say we want to retrieve all users who have at least one post with the title "Laravel". We can achieve this using the following query:
$users = User::whereHas('posts', function ($query) {
$query->where('title', '=', 'Laravel');
})->get();
In the above query, we are using the whereHas
method to filter users based on the existence of a post with the title "Laravel". The where
clause inside the anonymous function is used to filter the related posts.
whereDoesn'tHave
The whereDoesn'tHave
method is used to filter records based on the absence of a relationship. For example, let's say we want to retrieve all users who don't have any post with the title "Laravel". We can achieve this using the following query:
$users = User::whereDoesn'tHave('posts', function ($query) {
$query->where('title', '=', 'Laravel');
})->get();
In the above query, we are using the whereDoesn'tHave
method to filter users based on the absence of a post with the title "Laravel". The where
clause inside the anonymous function is used to filter the related posts.
Conclusion
In conclusion, whereHas
and whereDoesn'tHave
are powerful methods provided by Laravel to filter relationship data. They can be used to retrieve records based on the existence or absence of related records, respectively. Understanding these methods is essential when working with complex relationships in Laravel.