Skip to main content
Back to packages
1,515 GitHub stars

spatie/eloquent-sortable

View on GitHub

Description

Sortable behaviour for Eloquent models

To add sortable behaviour to your model you must:

  1. Implement the Spatie\EloquentSortable\Sortable interface.
  2. Use the trait Spatie\EloquentSortable\SortableTrait.
  3. Optionally specify which column will be used as the order column. The default is order_column.

Example

use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;
 
class MyModel extends Model implements Sortable
{
use SortableTrait;
 
public $sortable = [
'order_column_name' => 'order_column',
'sort_when_creating' => true,
];
 
// ...
}

If you don't set a value $sortable['order_column_name'] the package will assume that your order column name will be named order_column.

If you don't set a value $sortable['sort_when_creating'] the package will automatically assign the highest order number to a new model;

Assuming that the db-table for MyModel is empty:

$myModel = new MyModel();
$myModel->save(); // order_column for this record will be set to 1
 
$myModel = new MyModel();
$myModel->save(); // order_column for this record will be set to 2
 
$myModel = new MyModel();
$myModel->save(); // order_column for this record will be set to 3
 
 
//the trait also provides the ordered query scope
$orderedRecords = MyModel::ordered()->get();

Recent Courses on Laravel Daily