PHP

Creating Reusable Query Filters with Laravel Eloquent Local Scopes

Define and apply local query scopes in your Eloquent models to encapsulate common query constraints, making your code cleaner and more maintainable.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // Define a local scope for 'published' posts
    public function scopePublished($query)
    {
        return $query->where('status', 'published');
    }

    // Define a local scope that accepts an argument for post type
    public function scopeOfType($query, string $type)
    {
        return $query->where('type', $type);
    }
}

// Usage examples:
// Retrieve all published posts
$publishedPosts = Post::published()->get();

// Retrieve all published articles
$publishedArticles = Post::ofType('article')->published()->get();

// Retrieve all draft news posts
$draftNews = Post::where('status', 'draft')->ofType('news')->get();
How it works: Local query scopes allow you to define common sets of constraints that can be easily reused throughout your application. This snippet shows how to create a simple `published` scope and a more flexible `ofType` scope that accepts an argument. By chaining these scopes, you can build complex queries in a clean, readable, and maintainable way, promoting the DRY principle.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs