PHPackages                             quadrubo/eloquent-autosort - 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. quadrubo/eloquent-autosort

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

quadrubo/eloquent-autosort
==========================

This is my package eloquent-autosort

1.0.1(3y ago)3130[2 PRs](https://github.com/Quadrubo/eloquent-autosort/pulls)MITPHPPHP ^8.1

Since Mar 10Pushed 2y ago1 watchersCompare

[ Source](https://github.com/Quadrubo/eloquent-autosort)[ Packagist](https://packagist.org/packages/quadrubo/eloquent-autosort)[ Docs](https://github.com/quadrubo/eloquent-autosort)[ RSS](/packages/quadrubo-eloquent-autosort/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (13)Versions (5)Used By (0)

Eloquent Autosort
=================

[](#eloquent-autosort)

[![Latest Version on Packagist](https://camo.githubusercontent.com/a8c7a15c54dfaa40afefb424780bc2234cbfa28a4aec47d80c4c52c5410a7bbd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f717561647275626f2f656c6f7175656e742d6175746f736f72742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/quadrubo/eloquent-autosort)[![GitHub Tests Action Status](https://camo.githubusercontent.com/3896e548d8564f4581b28874cd86028cb36d8fd3390694b11bcd108b1a908953/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f717561647275626f2f656c6f7175656e742d6175746f736f72742f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/quadrubo/eloquent-autosort/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/c2925f9d45a87e873e1f519b3373ac27709323f8934f8263fb3d71021b5e12cc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f717561647275626f2f656c6f7175656e742d6175746f736f72742f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/quadrubo/eloquent-autosort/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/1d7d869c784a074ed5df79244b8d6d212f86a209c9ba83c4a32220b963785547/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f717561647275626f2f656c6f7175656e742d6175746f736f72742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/quadrubo/eloquent-autosort)

This package provides sortable behaviour for Eloquent models using a trait.

The package is based on [spatie/eloquent-sortable](https://github.com/spatie/eloquent-sortable). See [here](https://github.com/spatie/eloquent-sortable/pull/115#issuecomment-957198291) why this is not merged.

Features
--------

[](#features)

- Automatic sorting on create
- Automatic sorting on update
- Automatic sorting on delete
- Grouping with unlimited Columns

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

[](#installation)

This package can be installed through Composer.

```
composer require quadrubo/eloquent-autosort
```

You can publish the config file with:

```
php artisan vendor:publish --tag="eloquent-autosort-config"
```

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

```
return [
    /*
     * Which column will be used as the order column.
     */
    '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 models should sort when updating.
     * When true, the package will automatically update the order of both the old and new group.
     */
    'sort_when_updating' => true,

    /**
     * Define if the models should sort when deleting.
     * When true, the package will fix the order within the current group when deleting.
     */
    'sort_when_deleting' => true,

    /**
     * Define the columns the model should be grouped by.
     * You can leave this empty and implement your own solution by overwriting
     * `buildSortQuery` and `hasChangedGroupAttributes`.
     */
    'groups' => [],
];
```

Usage
-----

[](#usage)

To add sortable behaviour to your model you must:

1. Implement the `Quadrubo\EloquentAutosort\Sortable` interface.
2. Use the trait `Quadrubo\EloquentAutosort\SortableTrait`.

### Example

[](#example)

```
use Quadrubo\EloquentSortable\Sortable;
use Quadrubo\EloquentSortable\SortableTrait;

class MyModel extends Model implements Sortable
{
    use SortableTrait;

    public $sortable = [
        'order_column_name' => 'order_column',
        'sort_when_creating' => true,
        'sort_when_updating' => true,
        'sort_when_deleting' => true,
        'groups' => [],
    ];

    // ...
}
```

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.

If you don't set a value `$sortable['sort_when_updating']` the package will automatically repair the order on update.

If you don't set a value `$sortable['sort_when_deleting']` the package will automatically repair the order on delete.

If you don't set a value `$sortable['groups']` groups will not be used.

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.
// note that when you use grouping, you should
// build the query first for this to be useful.
$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);
```

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 also move a model to a specific or the new position:

```
$myModel->moveToPosition(3);

// moves to a position using the value in your order_column attribute
$myModel->moveToNewPosition();
```

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 one or multiple grouping fields (usually a foreign key): `id, `**`user_id`**`, title, order_column` and you'd like the package to take it into considerations, you cann add the grouping fields to the `$sortable['groups']` array.

```
public $sortable = [
    'groups' => [
        'user_id',
    ],
];
```

This will restrict the calculations to the fields in the array.

### Replacing the groups functionality

[](#replacing-the-groups-functionality)

If you don't like the way the groups functionality is implemented, you can easily make your own.

1. Overwrite the `buildSortQuery` method to change the behaviour of how the query is build.
2. Overwrite the `hasChangedGroupAttributes` method to provide a way for the package to know when it should resort.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

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

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

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

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

[](#security-vulnerabilities)

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

Credits
-------

[](#credits)

- [Quadrubo](https://github.com/Quadrubo)
- [All Contributors](../../contributors)

Thanks to the [Spatie/Eloquent-Sortable Team](https://github.com/spatie/eloquent-sortable) for the base package functionality!

License
-------

[](#license)

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

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity14

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 56% 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 ~0 days

Total

2

Last Release

1158d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ba196f48134b1195242931006b23881084411f9bee6f2e36389822479ffb3333?d=identicon)[Quadrubo](/maintainers/Quadrubo)

---

Top Contributors

[![Quadrubo](https://avatars.githubusercontent.com/u/71718414?v=4)](https://github.com/Quadrubo "Quadrubo (14 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (6 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (5 commits)")

---

Tags

eloquentlaravellaravelQuadruboeloquent-autosort

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/quadrubo-eloquent-autosort/health.svg)

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

###  Alternatives

[dyrynda/laravel-model-uuid

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

4802.8M8](/packages/dyrynda-laravel-model-uuid)[spatie/laravel-model-flags

Add flags to Eloquent models

4301.1M1](/packages/spatie-laravel-model-flags)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

423715.4k1](/packages/clickbar-laravel-magellan)[spatie/laravel-sql-commenter

Add comments to SQL queries made by Laravel

1931.4M1](/packages/spatie-laravel-sql-commenter)[spatie/laravel-deleted-models

Automatically copy deleted records to a separate table

409109.8k4](/packages/spatie-laravel-deleted-models)[wnx/laravel-backup-restore

A package to restore database backups made with spatie/laravel-backup.

203330.1k2](/packages/wnx-laravel-backup-restore)

PHPackages © 2026

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