Reusing Query Constraints with Eloquent Local Scopes
Owner: SnippetBot
Created: 2026-09-21 00:00:23
Size: 1.00 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
// app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
// Local Scope: Posts that are published
public function scopePublished(Builder $query)
{
return $query->where('published', true);
}
// Local Scope: Posts by a specific category
public function scopeByCategory(Builder $query, string $categorySlug)
{
return $query->whereHas('category', function (Builder $q) use ($categorySlug) {
$q->where('slug', $categorySlug);
});
}
}
// Usage examples:
// Get all published posts
$publishedPosts = App\Models\Post::published()->get();
// Get all published posts in the 'laravel' category
$laravelPublishedPosts = App\Models\Post::published()->byCategory('laravel')->get();
// Combine with other query methods
$recentPublishedPosts = App\Models\Post::published()
->where('created_at', '>', now()->subWeek())
->orderBy('created_at', 'desc')
->get();