Laravel advanced | Query Scope

Safaetul Ahasan
1 min readFeb 18, 2023

--

  1. Scope method without argument
  2. Scope method with argument
  3. Calling scope method in Controller
  4. Scopes into Reusable Traits
  5. 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.

  1. Open a Model where you want to create scope method.
  2. Add scope prefix with the method name. (scopeActive):(scopeMethodname).
  3. 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.

--

--

Safaetul Ahasan
Safaetul Ahasan

No responses yet