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:
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.
For common filtering we need to define following properties in model:
- $fillable = Specify all the fields which are exists in your database.
- $likeFilterFields = Add list of fields on which you want to apply like filtering.
- $boolFilterFields = Add fields on which you want to Boolean filtering.
Now extend your AppModel class to User.php model class.
Finally all your controller code is moved to your AppModel and your controller will be like this.
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.