PHP
Apply Global Query Scopes to Eloquent Models
Automate common query constraints across all instances of an Eloquent model using global scopes, ensuring consistent data filtering and DRY code.
use App\Models\Post;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
// 1. Define the Global Scope class (e.g., app/Scopes/ActiveScope.php)
namespace App\Scopes;
class ActiveScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$builder->where('is_published', true);
}
}
// 2. Apply the Global Scope in your Model's boot method
// (e.g., app/Models/Post.php)
namespace App\Models;
use App\Scopes\ActiveScope;
class Post extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope(new ActiveScope);
}
}
// Usage (queries will automatically include 'where is_published = true')
$publishedPosts = Post::all();
$singlePublishedPost = Post::find(1);
// To remove a global scope for a specific query:
$allPosts = Post::withoutGlobalScope(ActiveScope::class)->get();
How it works: Global scopes allow you to add constraints to all queries for a given model. This is useful for automatically filtering 'active' or 'published' records. You define a class that implements the `Scope` interface, providing an `apply` method to modify the query builder. Then, you register this scope in your model's `boot` method or a service provider. Queries on the model will then automatically include this constraint, which can be temporarily removed using `withoutGlobalScope()`.