Skip to content

MatthiasDeWinter/eloquent-sortable

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Sortable behaviour for Eloquent models

Build Status Latest Stable Version SensioLabsInsight Scrutinizer Code Quality License Total Downloads

This package provides a trait that adds sortable behaviour to an Eloquent model.

The value of the ordercolumn of a new record of a model is determined by the maximum value of the ordercolumn of all records of that model + 1.

The package also provides a query scope to fetch all the records in the right order.

Installation

This package can be installed through Composer.

composer require spatie/eloquent-sortable

You must add this service provider:

// Laravel 4: app/config/app.php 
// Laravel 5: config/app.php

'providers' => [ 
	'...',
	'Spatie\EloquentSortable\SortableServiceProvider',
];

Usage

To add sortable behaviour to your model you must:

  1. specify that the model will conform to Spatie\EloquentSortable\SortableInterface
  2. use the trait Spatie\EloquentSortable\Sortable
  3. specify which column will be used as the ordercolumn

###example

use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableInterface;

class MyModel extends Eloquent implements SortableInterface
{

    use Sortable;

    public $sortable = [
        'order_column_name' => 'order_column',
    ];
    
    ...
}

If you don't set a value $sortable['order_column_name'] the package will asume that your order column name will be 'order_column';

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
$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 record_column value 1
 * the record for model id 1 will have record_column value 2
 * the record for model id 2 will have record_column value 3
 */
MyModel::setNewOrder([3,1,2]);

About

Sortable behaviour for Eloquent models

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%