Mahmoud Al-HabashOpen to new projects
  • WorkWork
  • ServicesServices
  • LabLab
  • WritingWriting
  • ContactContact
Amman--:--عربي
Writing/Laravel

Laravel Eloquent: whereHas Deep Filtering

Filter models based on their relationship conditions.

16 January 20261 min readLaravelاقرأ بالعربية

On this page

  1. Basic whereHas
  2. With Count
  3. Nested Relationships
  4. Or whereHas

Filter with whereHas:

Basic whereHas

php
$users = User::whereHas('posts', function ($query) {
    $query->where('is_published', true);
})->get();

With Count

php
$users = User::whereHas('posts', function ($query) {
    $query->where('is_published', true);
}, '>=', 5)->get();

Nested Relationships

php
$users = User::whereHas('posts.comments', function ($query) {
    $query->where('approved', true);
})->get();

Or whereHas

php
$users = User::whereHas('posts')
    ->orWhereHas('comments')
    ->get();
All articles

Keep reading

  • Laravel Action Classes Pattern16 January 20261 min read
  • Laravel Action Classes: Single Responsibility16 January 20261 min read
  • Laravel API Rate Limiting16 January 20261 min read