namespace App\Models; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; class Post extends Model { // Local Scope: prefix with 'scope' public function scopePublished(Builder $query) { return $query->where('published_at', '<=', now()); } public function scopePopular(Builder $query) { return $query->where('views', '>', 100); } // Global Scope: applies to ALL queries for the model unless explicitly removed protected static function booted() { static::addGlobalScope('recent', function (Builder $builder) { $builder->orderBy('created_at', 'desc'); }); } } // Usage of Local Scopes: $publishedPosts = App\Models\Post::published()->get(); $popularPublishedPosts = App\Models\Post::popular()->published()->get(); // Usage of Global Scope: // All Post queries will be ordered by 'created_at' desc by default $posts = App\Models\Post::all(); // Ordered by created_at desc // To remove a global scope for a specific query $postsWithoutRecentOrder = App\Models\Post::withoutGlobalScope('recent')->get(); // To remove all global scopes $postsWithoutAnyGlobalScopes = App\Models\Post::withoutGlobalScopes()->get();