Eloquent Sortable
Eloquent Sortable stats
- Downloads
- 8.8M
- Stars
- 1,272
- Open Issues
- 0
- Forks
- 128
Sortable behaviour for eloquent models
Spatie Eloquent Sortable
The Spatie Eloquent Sortable package is a Laravel tool that integrates seamlessly with Eloquent models to provide easy management of sortable entities. It allows developers to automatically handle the order of model entries in databases with minimal configuration.
Key Features
- Sortable Trait: Add sortable behavior to Eloquent models with a simple trait.
- Automatic Order Management: Automatically assigns the highest order number to new model instances.
- Customizable Order Column: Allows specification of a custom column to be used for storing order.
- Query Scope for Ordering: Includes a scope for retrieving models in their proper order.
- Reordering Capabilities: Methods to adjust the order of model instances directly from the model (
moveOrderUp,moveOrderDown, etc.). - Grouping Support: Facilitates sorting within grouped records, making it ideal for multi-tenant applications.
Installation
Install via Composer:
composer require spatie/eloquent-sortable
For Laravel versions below 5.5, manually register the service provider in your config/app.php:
'providers' => [ ... Spatie\EloquentSortable\EloquentSortableServiceProvider::class,];
Optionally, publish the configuration file:
php artisan vendor:publish --tag=eloquent-sortable-config
Usage
Implement the Sortable interface and use the SortableTrait in your model:
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, ];}
Retrieve ordered records:
$orderedRecords = MyModel::ordered()->get();
Reorder records:
MyModel::setNewOrder([1, 2, 3]);
Control sorting within specific groups by overriding buildSortQuery method in your model:
public function buildSortQuery(){ return static::query()->where('user_id', $this->user_id);}
Additional Tools and Support
- Integration Tests: Includes tests to ensure reliable integration.
- Changelog and Contributions: Active maintenance and detailed release notes available.
This package is part of a suite of open-source packages by Spatie, with continued development supported by their premium courses and products. For any further guidance, refer to the package's GitHub repository.