PHP
Implement Global Query Scopes for Eloquent Models
Apply universal query constraints automatically to all Eloquent queries for a model, useful for soft deleting, multi-tenancy, or status filtering.
namespace App\Models\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class ActiveScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$builder->where('status', 'active');
}
}
// In your Post model:
// use App\Models\Scopes\ActiveScope;
//
// class Post extends Model
// {
// protected static function booted()
// {
// static::addGlobalScope(new ActiveScope);
// }
// }
// Now, any query for Post will automatically include `where('status', 'active')`
$activePosts = \App\Models\Post::all();
// You can remove a global scope for a specific query
$allPostsIncludingInactive = \App\Models\Post::withoutGlobalScope(ActiveScope::class)->get();
How it works: Global scopes allow you to apply constraints to all queries executed for a given model. In this example, an `ActiveScope` is created to only fetch records with `status` set to 'active'. It's registered in the model's `booted` method. This centralizes common filtering logic, reducing repetition and ensuring consistency across your application. You can temporarily remove a global scope using `withoutGlobalScope` when needed for specific queries.