PHP
Applying Global Query Filters with Eloquent Global Scopes
Implement reusable, application-wide query constraints using Laravel Eloquent global scopes to automatically filter model queries, ensuring data consistency.
// App/Models/Post.php
use Illuminate\Database\Eloquent\Builder;
class Post extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope('published', function (Builder $builder) {
$builder->where('is_published', true);
});
}
}
// Usage elsewhere:
$publishedPosts = Post::all(); // Automatically applies 'is_published = true'
$allPosts = Post::withoutGlobalScope('published')->get(); // Bypasses the scope
$specificPost = Post::withoutGlobalScopes()->find(1); // Bypasses all global scopes
How it works: Global scopes allow you to add automatic constraints to all queries for a given model, ensuring data consistency across your application. This example defines a 'published' global scope on the Post model, so `Post::all()` will only retrieve published posts by default. It also shows how to temporarily remove global scopes when you need to fetch records that would otherwise be filtered.