Handle Reordering of Table Records in Filament Using a Custom Action
When working with Filament, you might need to reorder table records using a custom column name. This can be especially challenging when dealing with pivot tables, as Filament expects the column to exist on the resource’s table. In this article, i’ll walk you through a comprehensive solution using the Category resource, while also showing you how to apply this method to any page that requires table reordering.
Creating a Resource in Filament
For this example, we’ll create a Category
resource.
php artisan make:filament-resource Category
Setting Up the Table Function
First, let’s define the table function in the Category resource. This function configures the table to use a custom column for sorting and reordering.
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
public static function table(Table $table): Table
{
return $table
->query(function (Builder $query) {
return $query->orderBy('sequence', 'asc');
})
->defaultSort('sequence', 'asc')
->reorderable('sequence')
->columns([
Tables\Columns\TextColumn::make('name')
->label('Name')
->searchable(),
Tables\Columns\TextColumn::make('description')
->label('Description')
->searchable(),
])
->actions([
Tables\Actions\ViewAction::make(),
Tables\Actions\EditAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
Things to note from the code above
query
this method sorts the table data by a custom sequence column which is coming from a pivot table, this can be different depending on your use case.defaultSort
this method sets the default sorting column and orderreorderable
this method specifies the column used for reordering
Handling Reordering Action Manually
Filament expects the column used for reordering to be present on the resource’s table. However, for pivot tables, we need to handle reordering ourselves. Here’s the hack to achieve this:
In the ListCategories
page, add the following method:
public function reorderTable(array $order): void
{
// Custom logic to update the sequence in the pivot table
}
This method will allow you to manually handle the reordering of table records. Note that you will need to implement the logic to update the sequence column in your pivot table based on the new order.
If you are using a different model, you will need to add this method to the corresponding list page for your model. For instance, if you are working with a
Product
model, you would add the method to theListProducts
page.
By following these steps, you can effectively manage the reordering of table data in Filament using a custom column name and custom logic, even when dealing with complex scenarios like pivot tables. This approach ensures that your application remains flexible and maintains proper data integrity.