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

Filament Price Filter Laravel Package

codewithdennis/filament-price-filter

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require codewithdennis/filament-price-filter
    

    Publish config (optional):

    php artisan vendor:publish --tag="filament-price-filter-config"
    
  2. Basic Usage: Register the widget in your Filament resource's getTableWidgets():

    use CodeWithDennis\FilamentPriceFilter\Widgets\PriceFilter;
    
    public static function getTableWidgets(): array
    {
        return [
            PriceFilter::make()
                ->queryUsing(fn (Builder $query, $min, $max) => $query
                    ->whereBetween('price', [$min, $max])
                ),
        ];
    }
    
  3. First Use Case: Add to a product listing table to filter by price range. Example:

    PriceFilter::make('price')
        ->label('Price Range')
        ->min(0)
        ->max(1000)
    

Implementation Patterns

Common Workflows

  1. Dynamic Range Filtering:

    PriceFilter::make('price')
        ->queryUsing(fn ($query, $min, $max) => $query
            ->where(function ($q) use ($min, $max) {
                if ($min) $q->where('price', '>=', $min);
                if ($max) $q->where('price', '<=', $max);
            })
        )
    
  2. Integration with Existing Filters: Combine with other Filament widgets (e.g., SelectFilter):

    public static function getTableWidgets(): array
    {
        return [
            PriceFilter::make('price'),
            SelectFilter::make('category')
                ->options(['electronics', 'clothing'])
        ];
    }
    
  3. Custom Currency Handling: Override globally in config/filament-price-filter.php:

    'currency' => 'EUR',
    'cents' => false,
    

    Or per-instance:

    PriceFilter::make('price')
        ->currency('GBP')
        ->hideCents()
    
  4. Localization: Publish translations:

    php artisan vendor:publish --tag="filament-price-filter-translations"
    

    Override in resources/lang/vendor/filament-price-filter/....


Advanced Patterns

  1. Multi-Column Filtering: Filter by multiple price-related columns (e.g., base_price, discounted_price):

    PriceFilter::make(['base_price', 'discounted_price'])
        ->queryUsing(fn ($query, $min, $max) => $query
            ->where(function ($q) use ($min, $max) {
                $q->where(function ($q) use ($min, $max) {
                    $q->where('base_price', '>=', $min)
                      ->orWhere('discounted_price', '>=', $min);
                })
                  ->where(function ($q) use ($min, $max) {
                      $q->where('base_price', '<=', $max)
                        ->orWhere('discounted_price', '<=', $max);
                  });
            })
        )
    
  2. Conditional Filtering: Enable/disable based on user role or context:

    PriceFilter::make('price')
        ->visible(fn () => auth()->user()->can('view_prices'))
    
  3. API Integration: Use the same filter logic in API routes:

    $min = request('min_price');
    $max = request('max_price');
    $query->whereBetween('price', [$min, $max]);
    

Gotchas and Tips

Pitfalls

  1. Query Builder Conflicts:

    • Ensure queryUsing returns a valid Builder instance. Test with dd($query) if filtering fails.
    • Avoid mixing whereBetween with null values (e.g., whereBetween('price', [null, 100]) will fail).
  2. Decimal Precision:

    • If using cents: false, prices are rounded to integers. Ensure your database column matches (e.g., DECIMAL(10,0) vs DECIMAL(10,2)).
  3. Translation Overrides:

    • Published translations may not reflect changes in the package. Clear cached views after updates:
      php artisan view:clear
      
  4. Performance:

    • Complex queryUsing logic can impact performance. Test with DB::enableQueryLog() to analyze queries:
      $query->toSql(); // Inspect generated SQL
      

Debugging Tips

  1. Log Filter Values: Add debug output to queryUsing:

    ->queryUsing(fn ($query, $min, $max) => {
        \Log::info("Price filter applied: min=$min, max=$max");
        return $query->whereBetween('price', [$min, $max]);
    })
    
  2. Check Config: Verify config/filament-price-filter.php for unexpected behavior (e.g., currency symbols).

  3. Widget Visibility: If the filter doesn’t appear, check:

    • The resource’s getTableWidgets() method.
    • Permissions (visible() callback).
    • Table columns (ensure the filtered column exists).

Extension Points

  1. Custom UI: Extend the widget’s view (resources/views/vendor/filament-price-filter/...) or use modifyQueryUsing to alter the underlying query logic.

  2. Additional Features: Add presets (e.g., "Under $50", "$50-$100"):

    PriceFilter::make('price')
        ->presets([
            'under_50' => ['min' => 0, 'max' => 50],
            '50_to_100' => ['min' => 50, 'max' => 100],
        ])
    
  3. Local Storage: Persist filter state using Filament’s useForm:

    use Filament\Forms\Components\Hidden;
    
    public static function getTableWidgets(): array
    {
        return [
            PriceFilter::make('price')
                ->extraInput(Hidden::make('min_price')->column('min_price')),
            // ...
        ];
    }
    
  4. Testing: Test filters in PHPUnit:

    public function test_price_filter()
    {
        $widget = PriceFilter::make('price');
        $query = $widget->modifyQuery(
            Builder::make('products'),
            10, 100
        );
        $query->toSql(); // Assert expected SQL
    }
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours