Weave 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 Date Scopes Filter Laravel Package

aymanalhattami/filament-date-scopes-filter

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies:

    composer require aymanalhattami/filament-date-scopes-filter laracraft/laravel-date-scopes
    
    • The package depends on laracraft/laravel-date-scopes, so ensure your models use date scopes (e.g., use Laracraft\DateScopes\HasDateScopes;).
  2. Publish Translations (Optional):

    php artisan vendor:publish --tag="filament-date-scopes-filter-translations"
    
    • Useful for customizing labels or supporting additional languages (e.g., Arabic).
  3. First Use Case: Add the filter to a Filament table resource:

    use AymanAlhattami\FilamentDateScopesFilter\DateScopeFilter;
    
    public static function table(Table $table): Table
    {
        return $table
            ->filters([
                DateScopeFilter::make('created_at'), // Replace with your timestamp column
            ]);
    }
    
    • This adds a dropdown with all date scopes (seconds, minutes, hours, etc.) to filter records.

Implementation Patterns

Common Workflows

  1. Basic Filtering:

    DateScopeFilter::make('published_at') // Filters by a custom column
        ->label('Publication Date'); // Custom label
    
    • Works seamlessly with Filament’s table filters.
  2. Excluding Scopes:

    DateScopeFilter::make('updated_at')
        ->withoutSeconds()
        ->withoutMinutes()
        ->withoutHours();
    
    • Hide granular scopes (e.g., for a "Reports" table where hourly data isn’t needed).
  3. Multi-Column Filtering:

    $table->filters([
        DateScopeFilter::make('start_date'),
        DateScopeFilter::make('end_date'),
    ]);
    
    • Combine filters for range-based queries (e.g., "Show events between two dates").
  4. Dynamic Scopes: Use laravel-date-scopes to define custom scopes in your model:

    // In your model
    use HasDateScopes;
    
    protected $dateScopes = [
        'custom_scope' => 'whereDate(\'created_at\', \'=\', $date)',
    ];
    

    Then reference them in the filter:

    DateScopeFilter::make('created_at')->scopes(['custom_scope']);
    
  5. Integration with Actions: Chain filters with actions (e.g., export filtered data):

    $table->actions([
        Tables\Actions\ExportAction::make(),
    ]);
    

Advanced Patterns

  1. Conditional Scopes: Dynamically adjust available scopes based on user roles or context:

    DateScopeFilter::make('created_at')
        ->scopes(fn () => auth()->user()->isAdmin() ? ['all'] : ['daily']);
    
  2. Custom UI: Override the default dropdown with a custom component:

    DateScopeFilter::make('created_at')
        ->customComponent(MyCustomDateScopeComponent::class);
    
  3. Localization: Extend translations for non-English locales:

    // config/filament-date-scopes-filter.php
    'translations' => [
        'es' => [
            'seconds' => 'Segundos',
            // ...
        ],
    ];
    

Gotchas and Tips

Pitfalls

  1. Missing laravel-date-scopes:

    • Error: Class 'HasDateScopes' not found.
    • Fix: Install laracraft/laravel-date-scopes and ensure models use HasDateScopes.
  2. Column Mismatch:

    • Error: Filter fails silently if the column doesn’t exist or isn’t a timestamp.
    • Fix: Verify the column name and type (e.g., created_at must be DATE/DATETIME).
  3. Scope Overlap:

    • Issue: Applying multiple filters with overlapping scopes (e.g., hours and days) may cause unexpected queries.
    • Fix: Use without* methods to exclude redundant scopes or test queries with dd($query).
  4. Translation Conflicts:

    • Issue: Custom translations may not load if the publish step is skipped.
    • Fix: Run php artisan vendor:publish and clear cached views (php artisan view:clear).
  5. Filament Version Mismatch:

    • Issue: The package supports Filament 4/5. Using an unsupported version may break UI.
    • Fix: Check the releases for compatibility.

Debugging Tips

  1. Query Inspection: Use Filament’s query logging to debug scope application:

    // In your model
    protected static function booted()
    {
        static::addGlobalScope(new \Illuminate\Database\Eloquent\Scope {
            public function apply($query, \Illuminate\Database\Eloquent\Model $model)
            {
                \Log::info('Query:', [$query->toSql(), $query->getBindings()]);
                return $query;
            }
        });
    }
    
  2. Scope Validation: Validate scopes in your model’s booted() method:

    public static function boot()
    {
        static::addGlobalScope(new \Laracraft\DateScopes\Scopes\DateScope);
        // Ensure scopes are registered before filtering
    }
    
  3. Performance:

    • Tip: For large datasets, limit scopes to broader ranges (e.g., withoutSeconds()) to reduce query complexity.
    • Tip: Use database indexes on filtered columns (e.g., created_at).

Extension Points

  1. Custom Scopes: Extend laravel-date-scopes to add domain-specific scopes (e.g., "this quarter"):

    // In your model
    public function scopeThisQuarter($query)
    {
        return $query->whereYear('created_at', date('Y'))
                    ->whereMonth('created_at', date('n'));
    }
    

    Then use it in the filter:

    DateScopeFilter::make('created_at')->scopes(['thisQuarter']);
    
  2. UI Customization: Override the filter’s Blade template:

    DateScopeFilter::make('created_at')
        ->view('custom.date-scope-filter');
    
    • Copy the default view from the package (resources/views/filament-date-scopes-filter/date-scope-filter.blade.php).
  3. Dynamic Column Mapping: Map database columns to user-friendly labels:

    DateScopeFilter::make('created_at')
        ->label('Record Creation Date');
    
  4. Event Listeners: Listen for filter changes to trigger side effects (e.g., update a dashboard):

    use AymanAlhattami\FilamentDateScopesFilter\Events\DateScopeFiltered;
    
    DateScopeFiltered::listen(function ($filter) {
        // Update analytics, etc.
    });
    
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.
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log
hsluv/hsluv
seampact/codegen
seampact/hooks
seampact/ir
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk