Good morning, and happy MonDEV!☕️
I hope you had a great weekend and are ready to get back to work. 😄
Is anyone out there working on some Laravel APIs this week? If so, I might have a useful tool to make your work a bit easier.
What am I talking about? It's this handy little library called Laravel Purity!
It's a lightweight package that resolves a rather nagging issue, not in terms of difficulty, but in terms of code verbosity. Indeed, Laravel Purity streamlines the process of filtering your models to the extreme, saving you from having to write out all the various types of filters and search methods for a given model.
By adding the "Filterable" trait to your Model and a "filter()" method in the endpoint where you return your model's list, you'll have access to a range of default parameters that can be used by the frontend to receive a filtered list.
The filter syntax might look somewhat familiar if you've ever worked with MongoDB in a project, even briefly. Here's a quick example:
Suppose you have an endpoint with a list of restaurants. This filter would allow you to filter them by name if they contain the text specified as a parameter. Besides
$contains, there are various other filters like $eq for checking equality,
$lt for comparing greater or less than relationships,
$in for checking if a parameter is inside an array provided by us, and many more. You can also use
$or to combine other filters and create more complex search scenarios.
Just to reiterate, all you need to do is add a
->filter() method in your controller. It might not be the ultimate solution for complex cases, but it certainly saves a lot of time on simpler but lengthy tasks, especially for pages with many different filters.
Moreover, if you don't want to make all types of filters available, you can enable or disable them at your discretion in the Purity config file. If you prefer to manage them case by case, you can configure them directly in the specific controller.
I strongly recommend this tool for its versatility and ease of implementation. It requires very little to be added to the project and used.
Have you ever tried it? Do you prefer to write everything from scratch, or do you willingly embrace tools like this that help you sidestep repetitive tasks? What do you look for in a tool before adopting it?
Let's discuss it in the comment if you want!
Have a great week, and happy coding 1_0! 😄