PHP

Applying Global Scopes for Eloquent Query Constraints

Learn to define and apply global query scopes in Laravel Eloquent to automatically add constraints to all queries for a given model, ensuring consistency.

// 1. Create a Global Scope Class (e.g., 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);
    }
}

// 2. Apply the Global Scope to a Model (e.g., app/Models/Post.php)
namespace App\Models;

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

class Post extends Model
{
    // Add this boot method
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(new PublishedScope);
    }

    protected $fillable = ['title', 'content', 'is_published'];
}

// 3. Example Usage (e.g., in a controller or route)
use App\Models\Post;

// This will automatically only fetch published posts
$publishedPosts = Post::all();

echo "Published Posts:
";
foreach ($publishedPosts as $post) {
    echo "- " . $post->title . " (Published: " . ($post->is_published ? 'Yes' : 'No') . ")
";
}

// To remove the global scope for a specific query
$allPosts = Post::withoutGlobalScope(PublishedScope::class)->get();

echo "
All Posts (including unpublished):
";
foreach ($allPosts as $post) {
    echo "- " . $post->title . " (Published: " . ($post->is_published ? 'Yes' : 'No') . ")
";
}

// Or remove all global scopes
// $allPosts = Post::withoutGlobalScopes()->get();
How it works: Global scopes allow you to add constraints to all queries for a given model. This is useful for enforcing application-wide rules, such as only retrieving "published" content or data belonging to a specific tenant. This snippet shows how to define a global scope class and then apply it in the model's `boot` method. It also demonstrates how to temporarily remove global scopes for specific queries 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