F
Filament2mo ago
ericmp

Sort table by random order

In my songs table, i want to add a filter to let the user choose to order the records randomly:
Tables\Filters\Filter::make('in_random_order')->query(fn (Builder $query): Builder => $query->inRandomOrder())
Tables\Filters\Filter::make('in_random_order')->query(fn (Builder $query): Builder => $query->inRandomOrder())
but if i check it or not, the results are the same. what could be happening? how can i make it to work?
Solution:
Okay, I got curious so I added a 2000 song table to a fresh filament installation and did some experimenting. got it to work by using baseQuery instead of query (https://filamentphp.com/docs/3.x/tables/filters/getting-started#modifying-the-base-query) : ```php ->filters([ Filter::make('Shuffle') ->toggle() ...
Jump to solution
7 Replies
nowak
nowak2mo ago
I think what you need to do, is to add a sorting column to your songs table, that you can use to: 1. Sort the records by in the table 2. Use a custom table header action to "randomly" shuffle the sort integers of your song records Then when you trigger your "Randomize" action, the sort would be shuffled, and your song records would appear to be shuffled as well as a result. This is basically what the filament reorder functionality does, but one by one.
ericmp
ericmpOP2mo ago
interesting approach, but what if there is thousands of songs, every time the action is clicked, for all thousands of songs ill have to update them to have a random integer in this new field? wouldnt that be expensive?
nowak
nowak2mo ago
Are you showing thousands of songs at once? You could just shuffle the songs shown in the current view. I don't know how expensive it would be to shuffle all songs in the database, might be worth trying out, though
ericmp
ericmpOP2mo ago
obv im not showing all at once, why would i only shuffle the songs in the current page? i want to shuffle them all
Solution
nowak
nowak2mo ago
Okay, I got curious so I added a 2000 song table to a fresh filament installation and did some experimenting. got it to work by using baseQuery instead of query (https://filamentphp.com/docs/3.x/tables/filters/getting-started#modifying-the-base-query) :
->filters([
Filter::make('Shuffle')
->toggle()
->baseQuery(fn (Builder $query) => $query->inRandomOrder())
->label('Shuffle Songs'),
])
->filters([
Filter::make('Shuffle')
->toggle()
->baseQuery(fn (Builder $query) => $query->inRandomOrder())
->label('Shuffle Songs'),
])
nowak
nowak2mo ago
example:
ericmp
ericmpOP2mo ago
oh god yeah idk why i was using ->query changing it to ->baseQuery did the trick thanks @nowak !
Want results from more Discord servers?
Add your server