skip to Main Content

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?

2

Answers


  1. Use conditional clauses.

    ->modifyQueryUsing(function (Builder $query) {
        $query->when($tableFilter, function (Builder $query) {
            $query->with('studentAcademics');
        }, function (Builder $query) {
            $query->whereNull('id');
        });
    });
    
    Login or Signup to reply.
  2. It worked in my case:

    ->modifyQueryUsing(function (Builder $query, Table $table) { 
        $filters = $table->getFilters();
    
        // Check if any filters are applied
        $hasActiveFilters = collect($filters)
                            ->some(fn ($filter) => $filter->isActive());
    
        if ($hasActiveFilters) {
            // If filters are active, modify the query accordingly
            return $query->with('studentAcademics');
        } else {
            // If no filters are active, apply a different query modification
            return $query->whereNull('id');
        }
    })
    

    To check if there is an active table filter in Laravel Filament and modify the Eloquent query accordingly, you can use the getFilters method within the modifyQueryUsing method

    getFilters: Retrieves all filters applied to the table.

    isActive: Checks if a specific filter is currently active.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search