Laravel: Common Filters using Model Scope

Lakhwinder Singh
Jun 4 · 2 min read

In Laravel, we commonly face the problem of adding repetitive filtering in Controllers. While working in controller classes, need to add repetitive filtering. In that case we add number of Where Statements, which make our code very lengthy and less readable.

Here is the example code of our controller if we have number of filtering params.

Let me take a case where we have users table and we need to add filtering on following field:

  • role_id
  • name
  • email
  • status

UsersController.php

And like above UsersController we did same thing in every controller for simple types of filtering.

To solve this type of problem, I prefer Laravel Models Scopes. Laravel Scope methods provide us to wrap some code of functionality inside model function. So that we can re-use that again and again where we want (only for models).

To achieve this we need to create AppModel which will extend Laravel Eloquent Base Model class and extend that AppModel class in every model (User/Post/Comment) instead of Eloquent Model.

AppModel.php

For common filtering we need to define following properties in model:

  1. $fillable = Specify all the fields which are exists in your database.
  2. $likeFilterFields = Add list of fields on which you want to apply like filtering.
  3. $boolFilterFields = Add fields on which you want to Boolean filtering.

Now extend your AppModel class to User.php model class.

User.php

Finally all your controller code is moved to your AppModel and your controller will be like this.

UsersController.php

Now when ever you will create new Model like Post.php then you need to extend AppModel. After that scopeFilter function can be accessed directly in your controller.

And here the main benefit is that if we want some different type of filtering for any other model. Then we need to just copy that function and paste to the model(in which you want to change filtering process), and that’s it!! you can make changes according to your requirement.

Lakhwinder Singh

Written by

Certified Laravel Developer . Working as Full Stack Web Developer.