Laravel Eloquent Queries are the Best ones. We are used. Eg: Post::all();
this returns all records. But we need to build our custom queries and use that where we want. So here Laravel provides a solution. That call Model Scope.
If you are writing eloquent queries in your Laravel project and write the same logic in your queries repeatedly, then query scopes might be of use to you. Laravel provides a solution for wrapping your conditions into a readable and reusable statement called Scopes.
Laravel has two scopes: Local Scope and Global Scope.
This article only discusses Local Scopes.
Here we will see, How to integrate scope. I want to return active Posts from $activePosts = Post::where('active', true)->get();
.
But I need the same thing in any other module as well. So I need to write again and again this where queries. Here is the solution. That call Scope.
Go to app \ Post.php or app \ Models \ Post.php (Laravel 8.x) file.
class Post extends Model {
public function scopeActive($query)
{
return $query->where('active', 1);
}
}
Laravel knows scope as an alias. With the scope defined above, like this:$activePosts = Post::active()->get();
Create Dynamic Scope
Go to app \ Post.php or app \ Models \ Post.php (Laravel 8.x) file. We can pass parameters for this scope.
class Post extends Model {
public function scopeActive($query, $value)
{
return $query->where('active', $value);
}
}
With the input parameter defined, like this:
// Get active posts
$activePosts = Post::active(true)->get();
Relationship with Scope
Go to app \ Post.php or app \ Models \ Post.php (Laravel 8.x) file. We can use a scope with Relationship.
$category = Category::find(1);
$activePosts = $category->posts()->active(true)->get();
Also, You can use scope like this:
$activePosts = Category::with('posts')->whereHas('posts',function($query){
$query->active(true);
})->get();
Thank you for reading this article !!
Read Also: Eloquent ORM (Object Relational Mapping) in Laravel
If you have any queries or doubts about this topic please feel free to contact us. We will try to reach you.