Laravel Purity

repository·master·Indexed 19 days ago

https://github.com/abbasudo/laravel-purity

An elegant package for Laravel that simplifies complex data filtering and sorting logic for Eloquent queries. It allows URL query string parameters to drive database queries, featuring over 20 predefined filtering methods, support for related models, and direct integration with Laravel Livewire. Version 3.3.2 provides capabilities to restrict, rename, and customize filterable and sortable fields via model properties or query builder methods.

Tokens
10K
Snippets
47
Records
53
Agent score
64%

What's inside laravel-purity

  1. Overview of Laravel Purity

    master

    Laravel Purity is a package designed to simplify complex data filtering and sorting logic for Eloquent queries in Laravel. It allows frontend users to apply filters and sorting via URL query string parameters. The package's filtering and sorting syntax is inspired by Strapi's API functionality.

    // Basic usage pattern
    $posts = Post::filter()->get();
  2. Overview of Laravel Purity features

    master

    Laravel Purity is a package designed to simplify and enhance query construction in Laravel applications. Key features include:

    • Simplicity: Focused on ease of use.
    • Rename and Restrict: Allows for elegant customization and control over which fields are queryable.
    • Predefined Methods: Provides over 20 filtering methods to refine queries.
    • Relation Friendly: Supports filtering and sorting through columns in related models.
    • Livewire Support: Integrates directly with Laravel Livewire.
    • Multi-column Friendly: Enables filtering and sorting data across multiple columns easily.
  3. Key features of Laravel Purity

    master

    Laravel Purity provides several advanced capabilities for managing Eloquent queries:

    • Livewire support: Seamless integration with Livewire components.
    • Field Management: Ability to rename and restrict which fields can be filtered.
    • Advanced Filtering: Various filter methods and the ability to filter by columns in related models.
    • Customization: Support for creating custom filters.
    • Sorting: Multi-column sorting capabilities.
    • Frontend Friendly: Works well with the JavaScript qs package for constructing query strings.
  4. Restrict filters for specific fields

    master

    Purity allows you to restrict which operators can be applied to specific model fields. There are three ways to implement this, listed from lowest to highest priority:

    1. $filterFields property: Define allowed operators per field. Note that if you use this method, you must define all fields in the model, even those without restrictions.
    2. $restrictedFilters property: Define restrictions for specific fields. Unlike $filterFields, you only need to list the fields you wish to restrict.
    3. restrictedFilters() builder method: Set restrictions directly on the Eloquent builder. This has the highest priority and overwrites all other methods.

    Important: Field restrictions are still subject to the global/model $filters whitelist. You cannot restrict a field to an operator that is not permitted in the model's general $filters array.

    // Method 1: $filterFields property
    $filterFields = [
      'title' => ['$eq'],  // title limited to eq
      'title' => '$eq',    // single operator
      'title:$eq',         // shorthand
      'title',             // no restriction
    ];
    
    // Method 2: $restrictedFilters property
    $restrictedFields = [
      'title' => ['$eq'],
      'title:$eq,$in',
      'title'
    ];
    
    // Method 3: Eloquent builder method (Highest Priority)
    Post::restrictedFilters(['title' => ['$eq']])->filter()->get();
  5. How Laravel Purity works

    master

    Laravel Purity allows you to simplify complex Eloquent filtering and sorting logic by enabling query string parameters to drive your database queries.

    To use it, you call the filter() method on an Eloquent model or query builder. Once filter() is added, the package automatically maps URL query string parameters to your model's filtering logic. For example, a request like ?filters[column_name][operator]=value will be processed by the package to apply that filter to the query.

    // 1. Add filter() to your Eloquent query
    $posts = Post::filter()->get();
    
    // 2. The query is now automatically filtered by URL parameters,
    // e.g., GET /api/posts?filters[title][$contains]=Purity
  6. Change the source of filter and sort parameters

    master

    By default, Purity automatically retrieves filter parameters from the find index within the query parameters (e.g., GET /api/users?find[name][$eq]=John).

    You can override this default behavior by passing an explicit array of parameters directly into the filter() or sort() methods. This is useful when your parameters are located under a different key or are provided manually from a different source.

    // Default behavior: gets filters from 'find' query params
    // GET /api/users?find[name][$eq]=John
    Post::filter(request()->query('find'))->get();
    
    // Overriding default: passing custom params directly
    Post::filter(['title' => ['$eq' => 'good post']])->get();
    
    // Overriding sort: passing custom sort array
    Post::sort(['title', 'id:desc'])->get();
  7. Enable sorting on a model

    master

    To enable sorting capabilities on an Eloquent model, add the Abbasudo\Purity\Traits\Sortable trait to your model class. Once the trait is added, you can call the sort() method on your model's query builder in your controllers to apply sorting parameters from the request.

    use Abbasudo\\Purity\Traits\Sortable;
    
    class Post extends Model
    {
        use Sortable;
        
        //
    }
    
    // In your controller:
    return Post::sort()->get();
  8. Enable filtering on a model

    master

    To enable filtering capabilities on an Eloquent model, add the Abbasudo\Purity\Traits\Filterable trait to your model class. Once the trait is added, you can call the filter() method on your model's query builder in your controllers to apply requested filters from the request. By default, filter() allows access to all available filters defined for that model.

    use Abbasudo\Purity\Traits\Filterable;
    
    class Post extends Model
    {
        use Filterable;
        
        //
    }
    
    // In your controller:
    return Post::filter()->get();
  9. Rename sort fields using $sortFields

    master

    To allow clients to sort by names other than the actual database column names, you can provide a mapping within the $sortFields property on your Model.

    If you define 'mobile' => 'phone' in $sortFields, the client can send ?sort=phone to sort the results by the mobile database column. You can also include simple strings for fields that do not require renaming.

    // App\Models\User
    
    // The actual database column is 'mobile', but the client should use 'phone' for sorting.
    protected $sortFields = [
      'name',
      'mobile' => 'phone',
    ];
  10. Perform complex filtering with $and and $or

    master

    Complex filtering allows you to combine multiple conditions using logical operators like $or and $and. This is useful for requesting data that meets specific, non-linear criteria.

    To use $or, pass an array of objects to the $or key within the filters object. Each object in the array represents a set of conditions where if any one of them is met, the record is included.

    const qs = require('qs');
    const query = qs.stringify({
      filters: {
        $or: [
          { date: { $eq: '2020-01-01' } },
          { date: { $eq: '2020-01-02' } },
        ],
        author: { name: { $eq: 'Kai doe' } },
      },
    }, { encodeValuesOnly: true });
    
    await request(`/api/books?${query}`);