Skip to main content
Back to packages
1,513 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

Next.js Basics for Laravel Developers

11 lessons
58 min

Roles and Permissions in Laravel 13

14 lessons
57 min

Testing in Laravel 13 For Beginners

26 lessons
1 h 41 min read

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.