← Back to all snippets
PHP

Applying Universal Query Constraints with Eloquent Global Scopes

Discover how to automatically apply 'where' clauses or other constraints to all queries for a specific model using Laravel Eloquent global scopes.

<?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('published', true);
    }
}

// In your Model (e.g., app/Models/Post.php)
namespace App\Models;

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

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

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

// Example Usage:
$publishedPosts = Post::all(); // Automatically includes ->where('published', true)

$allPosts = Post::withoutGlobalScope(PublishedScope::class)->get(); // Fetches all posts, even unpublished
How it works: Global scopes allow you to add constraints to all queries executed for a given model. In this example, the `PublishedScope` ensures that only posts where the `published` column is true are retrieved by default. This is particularly useful for 'soft deletes' like functionality or multi-tenancy. You can temporarily remove global scopes using `withoutGlobalScope` or `withoutGlobalScopes` when needed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs