PHPackages                             spatie/eloquent-sortable - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. spatie/eloquent-sortable

ActiveLibrary[Database &amp; ORM](/categories/database)

spatie/eloquent-sortable
========================

Sortable behaviour for eloquent models

5.0.1(2mo ago)1.5k22.9M—2.5%13820MITPHPPHP ^8.2CI passing

Since Jul 15Pushed 4w ago18 watchersCompare

[ Source](https://github.com/spatie/eloquent-sortable)[ Packagist](https://packagist.org/packages/spatie/eloquent-sortable)[ Docs](https://github.com/spatie/eloquent-sortable)[ Fund](https://spatie.be/open-source/support-us)[ GitHub Sponsors](https://github.com/spatie)[ RSS](/packages/spatie-eloquent-sortable/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (6)Versions (57)Used By (20)

 [   ![Logo for eloquent-sortable](https://camo.githubusercontent.com/2d72cb25fd41a570c1269a3cbab80fc8ec0ce991c6bc72dbdda48ebef27fe910/68747470733a2f2f7370617469652e62652f7061636b616765732f6865616465722f656c6f7175656e742d736f727461626c652f68746d6c2f6c696768742e77656270)  ](https://spatie.be/open-source?utm_source=github&utm_medium=banner&utm_campaign=eloquent-sortable)Sortable behaviour for Eloquent models
======================================

[](#sortable-behaviour-for-eloquent-models)

[![Latest Version](https://camo.githubusercontent.com/dc972f67706fc0514415c2117eb20f5982a05cae49417da9ff1e808eed102d13/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f7370617469652f656c6f7175656e742d736f727461626c652e7376673f7374796c653d666c61742d737175617265)](https://github.com/spatie/eloquent-sortable/releases)[![GitHub Workflow Status](https://camo.githubusercontent.com/9dbbdebd280616aad210aeeeabe66de73d205d9873cc27f7e725ac0fa15b74a8/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7370617469652f656c6f7175656e742d736f727461626c652f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473)](https://camo.githubusercontent.com/9dbbdebd280616aad210aeeeabe66de73d205d9873cc27f7e725ac0fa15b74a8/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7370617469652f656c6f7175656e742d736f727461626c652f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Total Downloads](https://camo.githubusercontent.com/b6ac38b09365445c585412000c7bbbeabe0f51baf15128267eee6ce03cb2670d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f656c6f7175656e742d736f727461626c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/eloquent-sortable)

This package provides a trait that adds sortable behaviour to an Eloquent model.

The value of the order column of a new record of a model is determined by the maximum value of the order column of all records of that model + 1.

The package also provides a query scope to fetch all the records in the right order.

Spatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

Support us
----------

[](#support-us)

Learn how to create a package like this one, by watching our premium video course:

[![Laravel Package training](https://camo.githubusercontent.com/4c7f3720a29525e627f6004ee367e55def510e45d18e6bc974725812fa5cf257/68747470733a2f2f7370617469652e62652f6769746875622f7061636b6167652d747261696e696e672e6a7067)](https://laravelpackage.training)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Installation
------------

[](#installation)

> For Laravel 6.x or PHP 7.x, use version 3.x of this package.

This package can be installed through Composer.

```
composer require spatie/eloquent-sortable

```

In Laravel 5.5 and above the service provider will automatically get registered. In older versions of the framework just add the service provider in `config/app.php` file:

```
'providers' => [
    ...
    Spatie\EloquentSortable\EloquentSortableServiceProvider::class,
];
```

Optionally you can publish the config file with:

```
php artisan vendor:publish --tag=eloquent-sortable-config
```

This is the content of the file that will be published in `config/eloquent-sortable.php`

```
return [
  /*
   * The name of the column that will be used to sort models.
   */
  'order_column_name' => 'order_column',

  /*
   * Define if the models should sort when creating. When true, the package
   * will automatically assign the highest order number to a new model
   */
  'sort_when_creating' => true,

  /*
   * Define if the timestamps should be ignored when sorting.
   * When true, updated_at will not be updated when using setNewOrder
   */
  'ignore_timestamps' => false,
];
```

Usage
-----

[](#usage)

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

[](#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();
```

You can set a new order for all the records using the `setNewOrder`-method

```
/**
 * the record for model id 3 will have order_column value 1
 * the record for model id 1 will have order_column value 2
 * the record for model id 2 will have order_column value 3
 */
MyModel::setNewOrder([3,1,2]);
```

Optionally you can pass the starting order number as the second argument.

```
/**
 * the record for model id 3 will have order_column value 11
 * the record for model id 1 will have order_column value 12
 * the record for model id 2 will have order_column value 13
 */
MyModel::setNewOrder([3,1,2], 10);
```

You can modify the query that will be executed by passing a closure as the fourth argument.

```
/**
 * the record for model id 3 will have order_column value 11
 * the record for model id 1 will have order_column value 12
 * the record for model id 2 will have order_column value 13
 */
MyModel::setNewOrder([3,1,2], 10, null, function($query) {
    $query->withoutGlobalScope(new ActiveScope);
});
```

To sort using a column other than the primary key, use the `setNewOrderByCustomColumn`-method.

```
/**
 * the record for model uuid '7a051131-d387-4276-bfda-e7c376099715' will have order_column value 1
 * the record for model uuid '40324562-c7ca-4c69-8018-aff81bff8c95' will have order_column value 2
 * the record for model uuid '5dc4d0f4-0c88-43a4-b293-7c7902a3cfd1' will have order_column value 3
 */
MyModel::setNewOrderByCustomColumn('uuid', [
   '7a051131-d387-4276-bfda-e7c376099715',
   '40324562-c7ca-4c69-8018-aff81bff8c95',
   '5dc4d0f4-0c88-43a4-b293-7c7902a3cfd1'
]);
```

As with `setNewOrder`, `setNewOrderByCustomColumn` will also accept an optional starting order argument.

```
/**
 * the record for model uuid '7a051131-d387-4276-bfda-e7c376099715' will have order_column value 10
 * the record for model uuid '40324562-c7ca-4c69-8018-aff81bff8c95' will have order_column value 11
 * the record for model uuid '5dc4d0f4-0c88-43a4-b293-7c7902a3cfd1' will have order_column value 12
 */
MyModel::setNewOrderByCustomColumn('uuid', [
   '7a051131-d387-4276-bfda-e7c376099715',
   '40324562-c7ca-4c69-8018-aff81bff8c95',
   '5dc4d0f4-0c88-43a4-b293-7c7902a3cfd1'
], 10);
```

You can also move a model up or down with these methods:

```
$myModel->moveOrderDown();
$myModel->moveOrderUp();
```

You can also move a model to the first or last position:

```
$myModel->moveToStart();
$myModel->moveToEnd();
```

You can determine whether an element is first or last in order:

```
$myModel->isFirstInOrder();
$myModel->isLastInOrder();
```

You can swap the order of two models:

```
MyModel::swapOrder($myModel, $anotherModel);
```

### Grouping

[](#grouping)

If your model/table has a grouping field (usually a foreign key): `id, `**`user_id`**`, title, order_column`and you'd like the above methods to take it into considerations, you can create a `buildSortQuery` method at your model:

```
// MyModel.php

public function buildSortQuery()
{
    return static::query()->where('user_id', $this->user_id);
}
```

This will restrict the calculations to fields value of the model instance.

### Dispatched events

[](#dispatched-events)

Once a sort has been completed, an event (`Spatie\EloquentSortable\EloquentModelSortedEvent`) is dispatched that you can listen for. This can be useful for running post-sorting logic such as clearing caches or other actions that need to be taken after a sort.

The event has an `isFor` helper which allows you to conveniently check the Eloquent class that has been sorted.

Below is an example of how you can listen for this event:

```
use Spatie\EloquentSortable\EloquentModelSortedEvent as SortEvent;

class SortingListener
{
    public function handle(SortEvent $event): void {
        if ($event->isFor(MyClass::class)) {
            // ToDo: flush our cache
        }
    }
}
```

Tests
-----

[](#tests)

The package contains some integration/smoke tests, set up with Orchestra. The tests can be run via phpunit.

```
vendor/bin/phpunit
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

Alternatives
------------

[](#alternatives)

- [Listify](https://github.com/lookitsatravis/listify)
- [Rutorike-sortable](https://github.com/boxfrommars/rutorika-sortable)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

79

—

ExcellentBetter than 100% of packages

Maintenance90

Actively maintained with recent releases

Popularity74

Solid adoption and visibility

Community52

Growing community involvement

Maturity89

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 59.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~80 days

Recently: every ~65 days

Total

54

Last Release

86d ago

Major Versions

0.2.2 → 1.0.02015-02-13

1.1.2 → 2.0.02015-08-06

2.3.0 → 3.0.02016-10-21

3.11.0 → 4.0.02021-03-31

4.5.2 → 5.0.02026-02-12

PHP version history (9 changes)0.1.0PHP &gt;=5.4.0

2.2.0PHP &gt;=5.6.0

3.0.0PHP &gt;=7.0

3.5.0PHP ^7.2

3.8.3PHP ^7.3

3.10.0PHP ^7.3|^8.0

4.0.0PHP ^8.0

4.0.2PHP ^8.1

5.0.0PHP ^8.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (139 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (18 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (12 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (9 commits)")[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (9 commits)")[![Nielsvanpach](https://avatars.githubusercontent.com/u/10651054?v=4)](https://github.com/Nielsvanpach "Nielsvanpach (5 commits)")[![MatthiasDeWinter](https://avatars.githubusercontent.com/u/8791525?v=4)](https://github.com/MatthiasDeWinter "MatthiasDeWinter (4 commits)")[![patinthehat](https://avatars.githubusercontent.com/u/5508707?v=4)](https://github.com/patinthehat "patinthehat (3 commits)")[![driade](https://avatars.githubusercontent.com/u/5692232?v=4)](https://github.com/driade "driade (3 commits)")[![jimirobaer](https://avatars.githubusercontent.com/u/8984769?v=4)](https://github.com/jimirobaer "jimirobaer (3 commits)")[![mokhosh](https://avatars.githubusercontent.com/u/6499685?v=4)](https://github.com/mokhosh "mokhosh (3 commits)")[![pascalbaljet](https://avatars.githubusercontent.com/u/8403149?v=4)](https://github.com/pascalbaljet "pascalbaljet (3 commits)")[![riasvdv](https://avatars.githubusercontent.com/u/3626559?v=4)](https://github.com/riasvdv "riasvdv (3 commits)")[![stevebauman](https://avatars.githubusercontent.com/u/6421846?v=4)](https://github.com/stevebauman "stevebauman (2 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (2 commits)")[![patrickbrouwers](https://avatars.githubusercontent.com/u/7728097?v=4)](https://github.com/patrickbrouwers "patrickbrouwers (1 commits)")[![phh](https://avatars.githubusercontent.com/u/1304003?v=4)](https://github.com/phh "phh (1 commits)")[![Propaganistas](https://avatars.githubusercontent.com/u/6680176?v=4)](https://github.com/Propaganistas "Propaganistas (1 commits)")[![RalphMRivera](https://avatars.githubusercontent.com/u/1270019?v=4)](https://github.com/RalphMRivera "RalphMRivera (1 commits)")[![twickstrom](https://avatars.githubusercontent.com/u/775346?v=4)](https://github.com/twickstrom "twickstrom (1 commits)")

---

Tags

eloquentlaravelphpsorttraitlaravelmodeleloquentsortablesortbehaviour

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/spatie-eloquent-sortable/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-eloquent-sortable/health.svg)](https://phpackages.com/packages/spatie-eloquent-sortable)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[jedrzej/sortable

Sortable trait for Laravel's Eloquent models - sort your models using request parameters

54261.0k1](/packages/jedrzej-sortable)[jedrzej/pimpable

Laravel 4/5/6 package that allows to dynamically filter, sort and eager load relations for your models using request parameters

105179.0k1](/packages/jedrzej-pimpable)[sebastiaanluca/laravel-boolean-dates

Automatically convert Eloquent model boolean attributes to dates (and back).

40111.7k1](/packages/sebastiaanluca-laravel-boolean-dates)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
