PHP

Define and Apply Global Scopes in Laravel Eloquent

Learn to apply global query constraints to your Eloquent models. Automatically filter results across your application, ensuring consistency and reducing repetitive code.

// app/Scopes/PublishedScope.php
namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class PublishedScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('is_published', true);
    }
}

// app/Models/Post.php
namespace App\Models;

use App\Scopes\PublishedScope;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected static function booted()
    {
        static::addGlobalScope(new PublishedScope);
    }

    // To temporarily remove a global scope:
    // Post::withoutGlobalScope(PublishedScope::class)->get();
    // Post::withoutGlobalScopes()->get();
}

// Usage example
$publishedPosts = Post::all(); // Automatically applies 'is_published = true'

$allPostsIncludingUnpublished = Post::withoutGlobalScope(PublishedScope::class)->get();
How it works: Global scopes allow you to add constraints to all queries for a given model. This is useful for "soft deleting" items, multi-tenancy, or ensuring only "published" content is retrieved by default. You define a class that implements the `Scope` interface, and then apply it in the model's `booted` method using `static::addGlobalScope()`. You can temporarily remove global scopes using `withoutGlobalScope()` or `withoutGlobalScopes()`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs