Using Scope with Laravel
Laravel
Eloquent Queries are are Best one. We are used. Eg: Post::all(); this
is return all records. But we need build our custom queries and use that
where we want. So here laravel provide solution. That call Model Scope.
Here
we will see , How to integrate scope. I want return ‘ active’ Post from
posts table.Currently i using where queries like this.
$activePosts = Post::where('active', true)->get();
But i need same thing any other module also.So i need write again and again this where queries. Here is the solution. That call Scope.
class Post extends Model
{
public function scopeActive($query)
{
return $query->where('active', 1);
}
}
Laravel know
scope
as alias. Now i can get active posts using Post::active()->get();$activePosts = Post::active()->get();
Create Dynamic Scope
We can pass parameter for this Scope.
class Post extends Model {
public function scopeActive($query, $value)
{
return $query->where('active', $value);
}
}
Now we can use it dynamically .
// Get active posts
$activePosts = Post::active(true)->get();
// Get not active posts
$notActivePosts = Post::active(false)->get();
Scope with Relation
we can use scope with relationship.
$category = Category::find(1);
$activePost = $category->posts()->active(true)->get();
Thank you
Không có nhận xét nào: