using laravel scopes with relation code example
Example: Eloquent Query Scope on Relationships
Problem :
$activePosts = Post::where('active', true)->get();
Solution:
class Post extends Model
{
public function scopeActive($query)
{
return $query->where('active', 1);
}
}
$activePosts = Post::active()->get();
=======================================================
Create Dynamic Scope:
class Post extends Model
{
public function scopeActive($query, $value)
{
return $query->where('active', $value);
}
}
$activePosts = Post::active(true)->get();
$notActivePosts = Post::active(false)->get();
===========================================================
Scope with Relation :
$category = Category::find(1);
$activePost = $category->posts()->active(true)->get();