leparking / laravel-sortable
Laravel package to sort Eloquent models
Requires
- php: >=5.5.9
- illuminate/database: ~5.2
Requires (Dev)
- orchestra/testbench: ~3.0
- phpunit/phpunit: ~4.0
This package is not auto-updated.
Last update: 2024-11-09 19:45:47 UTC
README
A Laravel 5.2 package to sort Eloquent models.
Installation
Require the package with composer
composer require leparking/laravel-sortable
Add the service provider to config/app.php
'providers' => [ // ... LeParking\Sortable\SortableServiceProvider::class, ],
Configuration
Publish the default configuration file to config/sortable.php
php artisan vendor:publish
The settings in this file will apply to all sortable models, but can be
overridden on each model with the $sortable
property.
Here are the available settings with their defaults:
return [ // Name of the column that will store the position. 'column' => 'position', // If set to true, new models will be inserted at the first position. 'insert_first' => false, // A column name or an array of columns names to group sortable models. 'group_by' => false, ];
Usage
Your sortable models should implement the Sortable
interface and use the SortableTrait
.
use Illuminate\Database\Eloquent\Model; use LeParking\Sortable\Sortable; use LeParking\Sortable\SortableTrait; class Book extends Model implements Sortable { use SortableTrait; // Optional property to override default settings. protected $sortable = [ // ... ]; }
The database table must have an integer column to store the position.
Schema::create('books', function($table) { $table->integer('position')->unsigned(); });
The position
attribute will be filled automatically when creating new models.
$book = Book::create(); echo $book->position; // 1 $book2 = Book::create(); echo $book2->position; // 2
The SortableTrait
provides a query scope to retrieve models ordered by the
position column.
$books = Book::ordered(); $books = Book::ordered('desc');