Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here

Filament Table in Random Order: Shuffle the Song List

2024-10-30

Have you ever needed to show Filament table records in RANDOM order? A typical example would be to Shuffle songs, like in Spotify. Let's see how to do it.


Let's say, we have a Filament resource for a Song model where we show columns title and artist.

app/Filament/Resources/SongResource.php

public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('id')
->label('ID'),
Tables\Columns\TextColumn::make('title'),
Tables\Columns\TextColumn::make('artist'),
])
->filters([
//
])
->actions([
//
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}

The getHeaderActions() method in the list class adds header actions for the list page.

use Filament\Actions;
use Filament\Tables\Contracts\HasTable;
use Illuminate\Database\Eloquent\Builder;
 
protected function getHeaderActions(): array
{
return [
Actions\Action::make('Shuffle songs')
->icon('heroicon-o-arrow-path-rounded-square')
->action(function (HasTable $livewire) {
$livewire->getTable()->modifyQueryUsing(fn (Builder $query) => $query->inRandomOrder());
}),
];
}

So, for the action, we inject the list page and get a table from it. When we have the table, we can use methods from it. In this case, we modify the query to get records in a random order.

When the button is pressed, we can see that records are in random order, looking at the ID column.

A few of our Premium Examples: