PHP
Enforcing Universal Query Constraints with Eloquent Global Scopes
Learn to apply global query scopes in Laravel Eloquent to automatically add constraints to all queries of a given model, ensuring data consistency across your application.
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
// In App/Models/Post.php
class Post extends Model
{
protected static function boot()
{
parent::boot();
// Automatically add 'where is_published = true' to all Post queries
static::addGlobalScope('published', function (Builder $builder) {
$builder->where('is_published', true);
});
}
}
// Usage (only published posts by default)
$publishedPosts = Post::all(); // SELECT * FROM posts WHERE is_published = true
// Retrieve all posts, temporarily ignoring the 'published' global scope
$allPostsIgnoringSingleScope = Post::withoutGlobalScope('published')->get();
// Retrieve all posts, ignoring ALL global scopes for this query
$allPostsIgnoringAllScopes = Post::withoutGlobalScopes()->get();
// Example for illustration
foreach ($publishedPosts as $post) {
echo "Published Post: {$post->title}
";
}
foreach ($allPostsIgnoringSingleScope as $post) {
echo "All Post (ignoring published scope): {$post->title}
";
}
How it works: Global scopes provide a powerful way to enforce universal constraints on all queries for a given model. By defining `addGlobalScope` within the model's `boot` method, every query to `Post` will automatically include `where('is_published', true)`. This ensures data consistency without needing to manually add the condition everywhere. You can temporarily bypass a single global scope with `withoutGlobalScope('scopeName')` or all scopes with `withoutGlobalScopes()`.