laraveleloquentlaravel-livewirelaravel-filamentfilamentphp

How to change Laravel Filament Eloquent Query base on a condition?


I have a filament resource with a table. I want to change the table query based on the condition i.e. if there is a filter

->modifyQueryUsing(function (Builder $query){ 
     if (tableFilter) 
        { 
           return $query->with('studentAcademics'); 
        } 
     else
        { 
          return $query->whereNull('id'); 
        } 
    })

How can I check if there is an active table filter?


Solution

  • ->modifyQueryUsing(function (Builder $query, $livewire) {
            // Get filter states from the Livewire component (ListStudents)
            $filters = $livewire->tableFilters ?? [];
    
            // Check if any filter has a non-empty value
            $hasFilterApplied = collect($filters)
                ->flatten(1)
                ->filter(fn ($value) => filled($value))
                ->isNotEmpty();
    
            if (! $hasFilterApplied) {
                // Stop query from returning results until a filter is applied
                $query->whereRaw('1 = 0');
            }
    
            return $query;
        })
    
    this too works for Filament v4