Tricks

Reorder Table Records

Jul 5, 2022
diazsasak
Table builder, Admin panel, FAQ

This trick was submitted before the admin panel had reordering functionality. You can find out more about that in the docs.

  1. Install the spatie/eloquent-sortable package .

  2. Create table actions to move the record up and down:

Tables\Actions\Action::make('up')
->action(fn (YourModel $record) => $record->moveOrderUp()),
Tables\Actions\Action::make('down')
->action(fn (YourModel $record) => $record->moveOrderDown()),
  1. Make sure to sort the record by your order column on the resource List page / relation manager:
protected function getTableQuery(): Builder
{
return parent::getTableQuery()->orderBy('your_order_column');
}
avatar

even nicer:

->actions([
Action::make('')
->icon('heroicon-o-arrow-up')
->action(fn (Category $record) => $record->moveOrderUp()),
Action::make('.')
->icon('heroicon-o-arrow-down')
->action(fn (Category $record) => $record->moveOrderDown()),
]);

please note the secon icon doe snot show if make is set to empty string

avatar

Is there any way to use it with belong_to_many relationship?

I need to set the sort order in my relation table that is used to attach between 2 models.

avatar

Check out the documentation here: https://github.com/spatie/eloquent-sortable/tree/main#grouping

Use the buildSortQuery() function to create the query that pulls together all the records that the current record is a member of.

avatar

The Spatie ordering trait provides a scope for ordering, so you can do this for consistency:

protected function getTableQuery(): Builder
{
return parent::getTableQuery()->ordered();
}

The default ordering is ascending, but you can reverse that:

->ordered('desc')