PHP
Filter Parent Records Based on Related Model Conditions with `whereHas`
Learn to use Eloquent's `whereHas` method to filter parent models based on the existence and conditions of their related models, improving complex data retrieval.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
public function tasks()
{
return $this->hasMany(Task::class);
}
}
class Task extends Model
{
public function project()
{
return $this->belongsTo(Project::class);
}
}
// Usage example:
// Get projects that have at least one task:
// $projectsWithTasks = Project::has('tasks')->get();
// Get projects that have at least one *completed* task:
// $projectsWithCompletedTasks = Project::whereHas('tasks', function ($query) {
// $query->where('status', 'completed');
// })->get();
// Get projects that have tasks assigned to a specific user (e.g., user_id = 5):
// $projectsForUser = Project::whereHas('tasks', function ($query) {
// $query->where('assigned_to_user_id', 5);
// })->get();
How it works: The `whereHas` method allows you to filter results based on the existence of related models that meet certain conditions. Unlike `with`, which loads relationships, `whereHas` adds a constraint to the parent query itself. You pass the name of the relationship and a closure, where you can define additional query constraints on the related model. This is incredibly powerful for scenarios where you need to retrieve parent records only if their associated child records satisfy specific criteria, ensuring efficient and precise data fetching.