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:
but if i check it or not, the results are the same. what could be happening? how can i make it to work?
Solution:Jump to 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() ...
7 Replies
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.
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?
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
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
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) :
example:
oh god
yeah
idk why i was using
->query
changing it to ->baseQuery
did the trick
thanks @nowak !