eloquent query scope on relationships

Solutions on MaxInterview for eloquent query scope on relationships by the best coders in the world

showing results for - "eloquent query scope on relationships"
Giacomo
20 Feb 2019
1Problem :
2$activePosts = Post::where('active', true)->get();
3
4Solution: 
5
6class Post extends Model
7{
8    public function scopeActive($query)
9    {
10        return $query->where('active', 1);
11    }
12}
13
14$activePosts = Post::active()->get();
15=======================================================
16
17Create Dynamic Scope:
18
19class Post extends Model 
20{
21    public function scopeActive($query, $value)
22    {
23        return $query->where('active', $value);
24    }
25}
26
27// Get active posts
28$activePosts = Post::active(true)->get();
29
30// Get not active posts
31$notActivePosts = Post::active(false)->get();
32
33===========================================================
34
35Scope with Relation :
36
37$category = Category::find(1);
38$activePost = $category->posts()->active(true)->get();
39