Laravel Sortable
A Laravel 5.2 package to sort Eloquent models., (*1)
, (*2)
Installation
Require the package with composer, (*3)
composer require leparking/laravel-sortable
Add the service provider to config/app.php, (*4)
'providers' => [
// ...
LeParking\Sortable\SortableServiceProvider::class,
],
Configuration
Publish the default configuration file to config/sortable.php, (*5)
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., (*6)
Here are the available settings with their defaults:, (*7)
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., (*8)
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., (*9)
Schema::create('books', function($table) {
$table->integer('position')->unsigned();
});
The position attribute will be filled automatically when creating new models., (*10)
$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., (*11)
$books = Book::ordered();
$books = Book::ordered('desc');
Similar Packages