Eloquent Query Scope in Laravel
In this post we will give you information about Eloquent Query Scope in Laravel. Hear we will give you detail about Eloquent Query Scope in Laravel And how to use it also give you demo for it if it is necessary.
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 10.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 10.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 10.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 !!
Also see: 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.
Hope this code and post will helped you for implement Eloquent Query Scope in Laravel. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs