PHP
Implementing Global Scopes for Filtering Eloquent Models
Understand how to implement Laravel Eloquent global scopes to automatically apply query constraints, such as filtering soft-deleted records or tenant-specific data.
// In App\Models\Post.php
use Illuminate\Database\Eloquent\Builder;
protected static function booted()
{
static::addGlobalScope('published', function (Builder $builder) {
$builder->where('is_published', true);
});
}
// Usage:
$publishedPosts = App\Models\Post::all(); // Automatically applies 'is_published' = true
$allPostsIncludingDrafts = App\Models\Post::withoutGlobalScope('published')->get();
How it works: This code shows how to define a global scope named 'published' on the `Post` model. This scope automatically adds a `where('is_published', true)` condition to all queries involving the `Post` model, ensuring only published posts are retrieved by default. You can temporarily remove a global scope using `withoutGlobalScope` when needed, for example, to fetch all posts including drafts.