{"id":13396011,"url":"https://github.com/spatie/eloquent-sortable","last_synced_at":"2025-05-12T15:15:42.248Z","repository":{"id":454127,"uuid":"21866232","full_name":"spatie/eloquent-sortable","owner":"spatie","description":"Sortable behaviour for Eloquent models","archived":false,"fork":false,"pushed_at":"2025-04-08T15:00:12.000Z","size":200,"stargazers_count":1442,"open_issues_count":0,"forks_count":139,"subscribers_count":21,"default_branch":"main","last_synced_at":"2025-04-08T22:07:13.510Z","etag":null,"topics":["eloquent","laravel","php","sort","trait"],"latest_commit_sha":null,"homepage":"https://spatie.be/open-source/packages","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/spatie.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"spatie","custom":"https://spatie.be/open-source/support-us"}},"created_at":"2014-07-15T15:58:10.000Z","updated_at":"2025-04-08T21:51:07.000Z","dependencies_parsed_at":"2024-01-29T06:08:31.381Z","dependency_job_id":"c72f2fdd-ce4a-4152-b6d2-f6b2b92181b6","html_url":"https://github.com/spatie/eloquent-sortable","commit_stats":{"total_commits":204,"total_committers":49,"mean_commits":4.163265306122449,"dds":0.446078431372549,"last_synced_commit":"d6a6dc9a2da3c5e4da3bfcad90518029e8a01180"},"previous_names":[],"tags_count":48,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Feloquent-sortable","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Feloquent-sortable/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Feloquent-sortable/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Feloquent-sortable/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spatie","download_url":"https://codeload.github.com/spatie/eloquent-sortable/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250477812,"owners_count":21437049,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["eloquent","laravel","php","sort","trait"],"created_at":"2024-07-30T18:00:37.644Z","updated_at":"2025-04-23T17:11:14.311Z","avatar_url":"https://github.com/spatie.png","language":"PHP","funding_links":["https://github.com/sponsors/spatie","https://spatie.be/open-source/support-us"],"categories":["Popular Packages","PHP","Packages"],"sub_categories":["Database/Eloquent/Models"],"readme":"\u003cdiv align=\"left\"\u003e\n    \u003ca href=\"https://spatie.be/open-source?utm_source=github\u0026utm_medium=banner\u0026utm_campaign=eloquent-sortable\"\u003e\n      \u003cpicture\u003e\n        \u003csource media=\"(prefers-color-scheme: dark)\" srcset=\"https://spatie.be/packages/header/eloquent-sortable/html/dark.webp\"\u003e\n        \u003cimg alt=\"Logo for eloquent-sortable\" src=\"https://spatie.be/packages/header/eloquent-sortable/html/light.webp\" height=\"190\"\u003e\n      \u003c/picture\u003e\n    \u003c/a\u003e\n\n\u003ch1\u003eSortable behaviour for Eloquent models\u003c/h1\u003e\n\n[![Latest Version](https://img.shields.io/github/release/spatie/eloquent-sortable.svg?style=flat-square)](https://github.com/spatie/eloquent-sortable/releases)\n![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/spatie/eloquent-sortable/run-tests.yml?branch=main\u0026label=tests)\n[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)\n[![Total Downloads](https://img.shields.io/packagist/dt/spatie/eloquent-sortable.svg?style=flat-square)](https://packagist.org/packages/spatie/eloquent-sortable)\n    \n\u003c/div\u003e\n\nThis package provides a trait that adds sortable behaviour to an Eloquent model.\n\nThe 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.\n\nThe package also provides a query scope to fetch all the records in the right order.\n\nSpatie 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).\n\n## Support us\n\nLearn how to create a package like this one, by watching our premium video course:\n\n[![Laravel Package training](https://spatie.be/github/package-training.jpg)](https://laravelpackage.training)\n\nWe 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).\n\nWe 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).\n\n## Installation\n\n\u003e For Laravel 6.x or PHP 7.x, use version 3.x of this package.\n\nThis package can be installed through Composer.\n\n```\ncomposer require spatie/eloquent-sortable\n```\n\nIn 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:\n\n```php\n'providers' =\u003e [\n    ...\n    Spatie\\EloquentSortable\\EloquentSortableServiceProvider::class,\n];\n```\n\nOptionally you can publish the config file with:\n\n```bash\nphp artisan vendor:publish --tag=eloquent-sortable-config\n```\n\nThis is the content of the file that will be published in `config/eloquent-sortable.php`\n\n```php\nreturn [\n  /*\n   * The name of the column that will be used to sort models.\n   */\n  'order_column_name' =\u003e 'order_column',\n\n  /*\n   * Define if the models should sort when creating. When true, the package\n   * will automatically assign the highest order number to a new model\n   */\n  'sort_when_creating' =\u003e true,\n\n  /*\n   * Define if the timestamps should be ignored when sorting.\n   * When true, updated_at will not be updated when using setNewOrder\n   */\n  'ignore_timestamps' =\u003e false,\n];\n```\n\n## Usage\n\nTo add sortable behaviour to your model you must:\n1. Implement the `Spatie\\EloquentSortable\\Sortable` interface.\n2. Use the trait `Spatie\\EloquentSortable\\SortableTrait`.\n3. Optionally specify which column will be used as the order column. The default is `order_column`.\n\n### Example\n\n```php\nuse Spatie\\EloquentSortable\\Sortable;\nuse Spatie\\EloquentSortable\\SortableTrait;\n\nclass MyModel extends Model implements Sortable\n{\n    use SortableTrait;\n\n    public $sortable = [\n        'order_column_name' =\u003e 'order_column',\n        'sort_when_creating' =\u003e true,\n    ];\n\n    // ...\n}\n```\n\nIf you don't set a value `$sortable['order_column_name']` the package will assume that your order column name will be named `order_column`.\n\nIf you don't set a value `$sortable['sort_when_creating']` the package will automatically assign the highest order number to a new model;\n\nAssuming that the db-table for `MyModel` is empty:\n\n```php\n$myModel = new MyModel();\n$myModel-\u003esave(); // order_column for this record will be set to 1\n\n$myModel = new MyModel();\n$myModel-\u003esave(); // order_column for this record will be set to 2\n\n$myModel = new MyModel();\n$myModel-\u003esave(); // order_column for this record will be set to 3\n\n\n//the trait also provides the ordered query scope\n$orderedRecords = MyModel::ordered()-\u003eget();\n```\n\nYou can set a new order for all the records using the `setNewOrder`-method\n\n```php\n/**\n * the record for model id 3 will have order_column value 1\n * the record for model id 1 will have order_column value 2\n * the record for model id 2 will have order_column value 3\n */\nMyModel::setNewOrder([3,1,2]);\n```\n\nOptionally you can pass the starting order number as the second argument.\n\n```php\n/**\n * the record for model id 3 will have order_column value 11\n * the record for model id 1 will have order_column value 12\n * the record for model id 2 will have order_column value 13\n */\nMyModel::setNewOrder([3,1,2], 10);\n```\n\nYou can modify the query that will be executed by passing a closure as the fourth argument.\n\n```php\n/**\n * the record for model id 3 will have order_column value 11\n * the record for model id 1 will have order_column value 12\n * the record for model id 2 will have order_column value 13\n */\nMyModel::setNewOrder([3,1,2], 10, null, function($query) {\n    $query-\u003ewithoutGlobalScope(new ActiveScope);\n});\n```\n\n\nTo sort using a column other than the primary key, use the `setNewOrderByCustomColumn`-method.\n\n```php\n/**\n * the record for model uuid '7a051131-d387-4276-bfda-e7c376099715' will have order_column value 1\n * the record for model uuid '40324562-c7ca-4c69-8018-aff81bff8c95' will have order_column value 2\n * the record for model uuid '5dc4d0f4-0c88-43a4-b293-7c7902a3cfd1' will have order_column value 3\n */\nMyModel::setNewOrderByCustomColumn('uuid', [\n   '7a051131-d387-4276-bfda-e7c376099715',\n   '40324562-c7ca-4c69-8018-aff81bff8c95',\n   '5dc4d0f4-0c88-43a4-b293-7c7902a3cfd1'\n]);\n```\n\nAs with `setNewOrder`, `setNewOrderByCustomColumn` will also accept an optional starting order argument.\n\n```php\n/**\n * the record for model uuid '7a051131-d387-4276-bfda-e7c376099715' will have order_column value 10\n * the record for model uuid '40324562-c7ca-4c69-8018-aff81bff8c95' will have order_column value 11\n * the record for model uuid '5dc4d0f4-0c88-43a4-b293-7c7902a3cfd1' will have order_column value 12\n */\nMyModel::setNewOrderByCustomColumn('uuid', [\n   '7a051131-d387-4276-bfda-e7c376099715',\n   '40324562-c7ca-4c69-8018-aff81bff8c95',\n   '5dc4d0f4-0c88-43a4-b293-7c7902a3cfd1'\n], 10);\n```\n\nYou can also move a model up or down with these methods:\n\n```php\n$myModel-\u003emoveOrderDown();\n$myModel-\u003emoveOrderUp();\n```\n\nYou can also move a model to the first or last position:\n\n```php\n$myModel-\u003emoveToStart();\n$myModel-\u003emoveToEnd();\n```\n\nYou can determine whether an element is first or last in order:\n\n```php\n$myModel-\u003eisFirstInOrder();\n$myModel-\u003eisLastInOrder();\n```\n\nYou can swap the order of two models:\n\n```php\nMyModel::swapOrder($myModel, $anotherModel);\n```\n\n### Grouping\n\nIf your model/table has a grouping field (usually a foreign key): `id, `**`user_id`**`, title, order_column`\nand you'd like the above methods to take it into considerations, you can create a `buildSortQuery` method at your model:\n```php\n// MyModel.php\n\npublic function buildSortQuery()\n{\n    return static::query()-\u003ewhere('user_id', $this-\u003euser_id);\n}\n```\nThis will restrict the calculations to fields value of the model instance.\n\n### Dispatched events\n\nOnce a sort has been completed, an event (`Spatie\\EloquentSortable\\EloquentModelSortedEvent`) is dispatched that you\ncan listen for. This can be useful for running post-sorting logic such as clearing caches or other actions that\nneed to be taken after a sort.\n\nThe event has an `isFor` helper which allows you to conveniently check the Eloquent class that has been sorted.\n\nBelow is an example of how you can listen for this event:\n\n```php\nuse Spatie\\EloquentSortable\\EloquentModelSortedEvent as SortEvent;\n\nclass SortingListener\n{\n    public function handle(SortEvent $event): void {\n        if ($event-\u003eisFor(MyClass::class)) {\n            // ToDo: flush our cache\n        }\n    }\n}\n```\n\n## Tests\n\nThe package contains some integration/smoke tests, set up with Orchestra. The tests can be run via phpunit.\n\n```bash\nvendor/bin/phpunit\n```\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.\n\n## Security Vulnerabilities\n\nPlease review [our security policy](../../security/policy) on how to report security vulnerabilities.\n\n## Credits\n\n- [Freek Van der Herten](https://github.com/freekmurze)\n- [All Contributors](../../contributors)\n\n## Alternatives\n- [Listify](https://github.com/lookitsatravis/listify)\n- [Rutorike-sortable](https://github.com/boxfrommars/rutorika-sortable)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Feloquent-sortable","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspatie%2Feloquent-sortable","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Feloquent-sortable/lists"}