filamentphp / filament

A collection of beautiful full-stack components for Laravel. The perfect starting point for your next app. Using Livewire, Alpine.js and Tailwind CSS.
https://filamentphp.com
MIT License
19.03k stars 2.94k forks source link

n+1 in MultiSelectFilter #3123

Closed mohammadalizadeh10 closed 2 years ago

mohammadalizadeh10 commented 2 years ago

Package

filament/filament

Package Version

2.13.24

Laravel Version

9.19

Livewire Version

2

PHP Version

8

Bug description

hi, using MultiSelectFilter with relationship load all categories (where not working) and with option n+1 problem

Tables\Filters\MultiSelectFilter::make('category_id')
                    ->options(Category::where('type', Category::TYPE_CLUB)->get()->pluck('title', 'id')),

public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class)
                    ->where('type', Category::TYPE_CLUB);
    }

image

Steps to reproduce

No response

Relevant log output

No response

zepfietje commented 2 years ago

@mohammad2306, could you set up a repository with the minimal code needed to reproduce the problem? This allows us to fix the issue much quicker.

mohammadalizadeh10 commented 2 years ago

@zepfietje https://github.com/mohammad2306/filament-filter run php artisan migrate --seed and check category filter in news resource

zepfietje commented 2 years ago

@mohammad2306, this is not a bug. The many queries are caused by the filter options being retrieved internally. You should wrap your options query in a closure, and then it's fixed!

 Tables\Filters\MultiSelectFilter::make('category_id')
+    ->options(fn () => Category::where('type', Category::TYPE_NEWS)->get()->pluck('title', 'id')),
-    ->options(Category::where('type', Category::TYPE_NEWS)->get()->pluck('title', 'id')),