PHP
Querying Models Based on Related Records in Laravel Eloquent
Master how to query parent models based on the existence or specific conditions of their related records using Eloquent's `whereHas` and `doesntHave` methods.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
// Example Queries:
// 1. Get all users who have at least one post
$usersWithPosts = App\Models\User::has('posts')->get();
// 2. Get all users who have posts with a specific title
$usersWithSpecificPosts = App\Models\User::whereHas('posts', function ($query) {
$query->where('title', 'like', '%Laravel%');
})->get();
// 3. Get all users who have NO posts
$usersWithoutPosts = App\Models\User::doesntHave('posts')->get();
// 4. Get all users who have posts published after a certain date
$usersWithRecentPosts = App\Models\User::whereHas('posts', function ($query) {
$query->where('created_at', '>', now()->subDays(7));
})->get();
How it works: Eloquent provides powerful methods to query models based on their relationships. `has('relationship')` retrieves parent models that have at least one related record. `whereHas('relationship', callback)` allows you to add specific conditions to the related records. Conversely, `doesntHave('relationship')` fetches parent models that have no related records, enabling precise filtering based on relationship existence and attributes.