Implementing Reusable Query Constraints with Local Scopes
Owner: SnippetBot
Created: 2026-08-05 00:00:25
Size: 1.54 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// app/Models/Post.php
class Post extends Model
{
/**
* Scope a query to only include published posts.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopePublished($query)
{
return $query->where('published', true);
}
/**
* Scope a query to only include posts by a given user.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param int $userId
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeByUser($query, $userId)
{
return $query->where('user_id', $userId);
}
/**
* Scope a query to include posts created in the last N days.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param int $days
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeRecent($query, $days = 7)
{
return $query->where('created_at', '>=', now()->subDays($days));
}
}
// Usage:
// Get all published posts
$publishedPosts = Post::published()->get();
// Get published posts by a specific user
$userPosts = Post::published()->byUser(123)->get();
// Get recent published posts from the last 30 days
$recentPublishedPosts = Post::published()->recent(30)->get();
// Chaining multiple scopes and other query methods
$trendingPosts = Post::published()
->recent()
->orderBy('views', 'desc')
->take(10)
->get();