Defining and Using Global Scopes
Owner: SnippetBot
Created: 2026-07-12 00:00:17
Size: 0.73 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
// Example Model: App\Models\Post
class Post extends Model
{
// Define a global scope for 'published' posts
protected static function booted()
{
static::addGlobalScope('published', function (Builder $builder) {
$builder->where('is_published', true);
});
}
}
// Usage:
// Retrieves only published posts (global scope automatically applied)
$publishedPosts = Post::all();
// Retrieves all posts, including unpublished ones (removing the global scope)
$allPosts = Post::withoutGlobalScope('published')->get();
// Retrieve all posts, ignoring all global scopes
$allPostsIgnoringAllScopes = Post::withoutGlobalScopes()->get();