Sometimes you run into a situation when you have to reuse some of the conditions more, with the help of scopes we can easily reuse or create common functionality for particular queries.
Laravel scopes provide a way to define model functions that especially run on query methods. In this tutorial, we will show you how to define scopes in Laravel.
Scopes can be defined either in the model class or in a separate scope class, also a scope can be local, or global, and scope also can be dynamic.
There are two types of scopes available in Laravel:
- Global Scopes
- Local Scopes
Global scopes allow you to add constraints to all queries for a given model. The Laravel Soft Delete functionality works within a global scope. Which automatically skips deleted records.
While scopes like onlyTrashed or withTrashed work as local scopes which executes only when they are called by the user.
Creating Scopes in Laravel
Let’s take an example, we are creating functionality where users can be enabled or disabled based on status. For that, we have created a status column in the user’s table. We will create a scope that applies the active condition.
Open the User model and add the below code to it:
class User extends Model
{
public function scopeActive($query)
{
return $query->where('status', 1);
}
}
Here, we have created an active scope that will add a condition on the user model whenever it’s called. Let’s see how to call scopes while querying.
$users = User::get();
//To get active users
$users = User::active()->get();
Creating Dynamic Scopes in Laravel
We can also create dynamic scopes where we pass the parameter and perform queries on that parameter. Let’s create another scope into the user model to perform the same operation using the dynamic scope.
class User extends Model
{
public function scopeStatus($query, $arg)
{
return $query->where('status', $arg);
}
}
Here, we pass value while calling scope function like the below example:
//To get active users
$users = User::status(1)->get();
//To get inactive users
$users = User::status(0)->get();
Here, we have created a dynamic scope that checks value based on parameters.
Conclusion
In this article, you have learned about the types and use of scope and how to create scope and dynamic scopes. You can also use scopes with relations.