Laravel Tutorials

Eloquent Relationship Queries in Laravel with whereRelation

Published
Eloquent Relationship Queries in Laravel with whereRelation image

Laravel's whereRelation method streamlines the process of filtering models based on their relationships' attributes. This elegant approach replaces complex subqueries and joins with a more readable and maintainable syntax.

This feature proves especially valuable when building complex filters in e-commerce platforms, content management systems, or any application where models are interconnected and filtering based on related data is crucial.

Post::whereRelation('comments', 'is_approved', true)->get();

Here's an example of building a course filtering system:

<?php

namespace App\Http\Controllers;

use App\Models\Course;
use Illuminate\Http\Request;

class CourseController extends Controller
{
    public function browse(Request $request)
    {
        $courses = Course::query();
        // Filter by instructor rating
        if ($request->has('top_rated')) {
            $courses->whereRelation(
                'instructor',
                'rating',
                '>=',
                4.5
            );
        }

        // Filter by recent student reviews
        if ($request->has('well_reviewed')) {
            $courses->orWhereRelation(
                'reviews',
                'created_at',
                '>=',
                now()->subDays(30)
            );
        }

        // Filter by active discussion
        if ($request->has('active_discussion')) {
            $courses->whereRelation(
                'discussions',
                'last_activity',
                '>=',
                now()->subDays(7)
            );
        }
        return $courses->with(['instructor', 'reviews'])
            ->latest()
            ->paginate();
    }
}

The query builder creates efficient SQL based on your relationship conditions:

// Filters courses with:
// - Highly rated instructors (4.5+)
// - OR recent reviews
// - AND active discussions
$courses = Course::whereRelation('instructor', 'rating', '>=', 4.5)
    ->orWhereRelation('reviews', 'created_at', '>=', now()->subDays(30))
    ->whereRelation('discussions', 'last_activity', '>=', now()->subDays(7))
    ->get();

WhereRelation provides a clean, expressive way to filter models based on relationship attributes, leading to more maintainable code.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Slow Job Alerts and Replica Commit IDs in Laravel 13.40 image

Slow Job Alerts and Replica Commit IDs in Laravel 13.40

Read article
Flock: A Free, Native Herd Alternative for Laravel image

Flock: A Free, Native Herd Alternative for Laravel

Read article
Live Props for Real-Time Updates in Inertia.js v3.11 image

Live Props for Real-Time Updates in Inertia.js v3.11

Read article
Cooldown Dependency Policy now in Composer 2.11 image

Cooldown Dependency Policy now in Composer 2.11

Read article
Email Sending and Testing for Laravel in One Account image

Email Sending and Testing for Laravel in One Account

Read article
Decide with Jev: Tie Every AI Check to the Exact Draft image

Decide with Jev: Tie Every AI Check to the Exact Draft

Read article