Spatie Laravel Query Builder – Filter, sort, and include relationships in Eloquent queries

Spatie Laravel Query Builder is a package that allows you to easily build Eloquent queries by applying filters, sorting, and including relationships. This package simplifies the process of handling complex query parameters from API requests, enabling cleaner and more maintainable code.

 

Key Features of Spatie Laravel Query Builder:

  1. Filtering: Easily apply filters to your Eloquent queries based on request parameters.
  2. Sorting: Support for dynamic sorting of query results.
  3. Includes: Include related models and eager load relationships to optimize database queries.
  4. Customizable: Extend and customize query building logic to fit your application’s needs.
  5. Validation: Validate query parameters to ensure they conform to expected formats.

Installation

To get started with Spatie Laravel Query Builder, follow these steps:

  1. Require the Package: Install the package via Composer:
  2. Publish Configuration (Optional): You can publish the configuration file using:
     

Setting Up the Query Builder

  1. Basic Usage: To use the query builder in a controller, you first import the QueryBuilder class and then apply it to your Eloquent model. Here’s an example with a Post model:
  2. Allowed Filters: Specify which filters are allowed for your queries using allowedFilters(). You can filter based on fields in the model, and you can also create custom filters.
  3. Allowed Sorts: Define which fields can be sorted using allowedSorts():
  4. Including Relationships: Use allowedIncludes() to specify which relationships can be eagerly loaded:
     

Custom Filters

You can also create custom filters to handle more complex query logic. Here’s how to create a custom filter for filtering posts by a specific keyword in the title:

  1. Create a Filter Class: Use the php artisan make:filter command to create a custom filter:
  2. Implement the Filter Logic: In your filter class, implement the apply() method:
  3. Register the Custom Filter: Register your custom filter in the controller:
     

Conclusion

Spatie Laravel Query Builder is a powerful tool for efficiently building Eloquent queries with a focus on filtering, sorting, and including relationships. It helps keep your code clean and maintainable, especially when dealing with complex query logic.

 

Additional Considerations

  • Documentation: For more detailed information, advanced features, and configuration options, refer to the official Spatie Laravel Query Builder documentation.
  • Performance: Always test and optimize your queries, especially when dealing with large datasets or complex relationships.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top