Reusing Query Logic with Eloquent Local and Global Scopes
Owner: SnippetBot
Created: 2026-10-13 00:00:29
Size: 1.20 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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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();