Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Purity Laravel Package

abbasudo/laravel-purity

Laravel Purity adds elegant filtering and sorting to Eloquent queries. Just call filter() on a model query, then let clients apply complex conditions via URL query parameters (e.g., filters[title][$contains]=...). Great for clean, flexible APIs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:
    composer require abbasudo/laravel-purity
    php artisan vendor:publish --tag=purity
    
  2. Add Traits to Model:
    use Abbasudo\Purity\Traits\Filterable;
    use Abbasudo\Purity\Traits\Sortable;
    
    class Post extends Model
    {
        use Filterable, Sortable;
    }
    
  3. Apply in Controller:
    return Post::filter()->sort()->get();
    
  4. Frontend Usage:
    // Filter example
    const query = qs.stringify({
      filters: {
        title: { $contains: 'Purity' }
      }
    });
    
    // Sort example
    const sortQuery = qs.stringify({
      sort: ['title:asc', 'created_at:desc']
    });
    

First Use Case

Build a searchable API endpoint where users can filter and sort posts via URL parameters. Example:

GET /api/posts?filters[title][$contains]=Laravel&sort[0]=created_at:desc

Implementation Patterns

Core Workflows

  1. Basic Filtering:

    // Controller
    $posts = Post::filter()->get();
    
    // URL: /api/posts?filters[title][$eq]=Hello
    
    • Automatically parses $eq, $contains, $gt, etc. from query string.
  2. Sorting:

    // Controller
    $posts = Post::sort()->get();
    
    // URL: /api/posts?sort[0]=title:desc&sort[1]=created_at:asc
    
    • Supports multi-column sorting with :asc/:desc suffixes.
  3. Livewire Integration:

    // Component
    #[Url]
    public $filters = ['title' => []];
    
    public function render()
    {
        return Post::filter($this->filters)->get();
    }
    
    • Bind inputs to $filters array:
      <input wire:model.live="filters.title.$eq" placeholder="Exact title">
      
  4. Relation Handling:

    // Model
    public function tags(): HasMany { return $this->hasMany(Tag::class); }
    
    // Related Model (Tag)
    protected $filterFields = ['name']; // Restrict allowed fields
    
    • Filter/sort by relations via dot notation:
      // URL: /api/posts?filters[tags.name][$contains]=Tech
      

Integration Tips

  • API Resources: Use Purity::getFilters()/Purity::getSorts() to inspect applied filters/sorts in resource classes.
  • Validation: Extend PurityServiceProvider to add custom validation rules for filters.
  • Caching: Cache filtered/sorted queries if using get() with large datasets.
  • Testing: Mock Purity in tests by overriding filter()/sort() methods.

Gotchas and Tips

Pitfalls

  1. Field Restrictions:

    • $filterFields in v3+ restricts (not renames) fields. Use renameFields for aliases:
      protected $renameFields = ['published_at' => 'date'];
      
    • Gotcha: Forgetting to define $filterFields in related models breaks relation filtering.
  2. Silent Exceptions:

    • Defaults to silent: true in config. Set to false for debugging:
      'silent' => env('APP_DEBUG'), // Dynamic toggle
      
  3. Nested Relations:

    • Not supported: posts.tags.user.name will fail. Use flat dot notation (tags.name).
  4. Case Sensitivity:

    • $eq is case-insensitive; use $eqc for case-sensitive matches.
  5. URL Encoding:

    • Frontend must encode values (e.g., title:desctitle%3Adesc). Use qs library:
      qs.stringify({ sort: ['title:desc'] }, { encodeValuesOnly: true });
      

Debugging Tips

  • Inspect Filters/Sorts:
    $filters = Purity::getFilters(request());
    $sorts = Purity::getSorts(request());
    
  • Log Raw Input:
    \Log::debug('Raw filters:', request()->query('filters'));
    
  • Test with tinker:
    php artisan tinker
    >>> Post::filter()->toSql(); // See generated SQL
    

Extension Points

  1. Custom Filters:

    • Register via PurityServiceProvider:
      Purity::extend('custom', function ($query, $value) {
          return $query->where('column', 'LIKE', "%{$value}%");
      });
      
    • Use in URL: ?filters[column][custom]=value
  2. Dynamic Field Whitelisting:

    • Override getFilterFields() in model:
      public function getFilterFields(): array
      {
          return ['title', 'published_at'];
      }
      
  3. Silent Mode:

    • Disable silently failing invalid filters:
      Purity::setSilent(false);
      
  4. Livewire Debouncing:

    • Add debounce to inputs to avoid rapid API calls:
      <input wire:model.debounce.500ms.live="filters.title.$contains">
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony