Laravel Querying Relationships
A relationship query filters models through a relationship. It asks a question about the related rows, not about the model itself.
Users with tasks
Ana has tasks, so she stays in the list.
User::whereHas('tasks')->get();Users with an undone task
A closure inside whereHas adds a condition on the related rows. A relationship query filters models through a relationship.
User::whereHas('tasks', function ($query) {
$query->where('done', false);
})->get();Users with no tasks
doesntHave is the opposite of whereHas.
User::doesntHave('tasks')->get();Tasks of one user
A relationship query also works from the child side.
Task::whereHas('user', function ($query) {
$query->where('name', 'Ana');
})->get();Example
use App\Models\User;
use Illuminate\Support\Facades\Route;
Route::get('/l41/counts', function () {
return User::withCount('tasks')->orderBy('name')->get()
->map(fn ($user) => $user->name.': '.$user->tasks_count)
->implode(', ');
});Key points
- whereHas: filters models that have related rows.
- Use whereHas to keep only models with a matching relationship.
- Use withCount to count related rows without loading them.
- Use doesntHave to keep only models with no related rows.
In this example, the route loads every user with a task count. withCount adds a tasks_count column to each user. The map step turns each user into a short text line. The implode step joins the lines with commas. Open /l41/counts in the browser to see the output.
Note
A relationship name in a query must match the method name on the model.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does User::whereHas('tasks') return?