Filter API Responses with Laravel Purity

The Laravel Purity package is an elegant and efficient filtering and sorting package for Laravel, designed to simplify complex data filtering and sorting logic for eloquent queries. By simply adding filter() to your Eloquent query, you can add the ability for frontend users to apply filters based on URL query string parameters like a breeze.

Let's say that your controller returns a collection of books, and you want to allow filtering by category slug mystery:

return Book::filter()->with('category')->get();

Using this package, you can now make a request that targets the category slug or any other field you allow to be filtered:

/api/books?filters[category][slug][$eq]=mystery

The filtered response would only include books in the category with a slug of mystery now. Purity provides various filters for things like $in, $lt, $gt, etc.

Purity offers the following main features to make it a robust filtering and data sorting package for Eloquent models:

  • Livewire support (added in v2)
  • Rename and restrict fields (added in v2)
  • Various filter methods
  • Simple installation and usage
  • Filter by relation columns
  • Custom filters
  • Multi-column sort

Check out the Purity Documentation page for usage and setup instructions!


The post Filter API Responses with Laravel Purity appeared first on Laravel News.

Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.

Read more

© 2024 Extly, CB - All rights reserved.