Laravel advanced | Query Scope
1 min readFeb 18, 2023
- Scope method without argument
- Scope method with argument
- Calling scope method in Controller
- Scopes into Reusable Traits
- Conclusion
In Laravel, a scope is a way to define a reusable set of constraints for a query on a model. Scopes allow you to filter the results of a query based on certain conditions and can be used to retrieve specific data from the database. Scopes are defined on the model and are used by calling a method on the model’s query builder.
- Open a Model where you want to create scope method.
- Add
scope
prefix with the method name. (scopeActive):(scopeMethodname). - Create
scopeActive()
method that takes a single parameter$query
. Here,$query
is the Eloquent builder instance.
For example, you can define the scope on a User
model to only retrieve active users, like this:
class User extends Model {
public function scopeActive($query) {
return $query->where('active', true);
}
public function scopeActiveCity($query,$city){
return $query->where('active', true)
->where('city',$city)
->get();
}
}
Then in your controller, you can use this scope to retrieve active users like:
$users = User::active()->get();
$activecity = User::activeCity('Dhaka');
This will retrieve all the users where the active
column is true.