PHP code example of sudo520 / laravel-sortable

1. Go to this page and download the library: Download sudo520/laravel-sortable library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sudo520 / laravel-sortable example snippets


use Sudo520\LaravelSortable\Sortable;

class MyModel extends Eloquent
{
    use Sortable;

    protected $fillable = [
        ...
        'sort_index',
        ...
    ];

    ...
}



class CreateMyModelsTable extends Migration
{
    public function up()
    {
        Schema::create('my_models', function (Blueprint $table) {
            ...
            $table->unsignedInteger('sort_index');
            ...
        });
    }

    public function down()
    {
        Schema::dropIfExists('my_models');
    }
}


use Sudo520\LaravelSortable\Sortable;

class MyModel extends Eloquent
{
    use Sortable;

    public $sortIndexColumn = 'order';

    ...
}

use Sudo520\LaravelSortable\Sortable;

class MyModel extends Eloquent
{
    use Sortable;

    public $setSortIndexOnCreating = false;

    ...
}

use Sudo520\LaravelSortable\Sortable;

class Post extends Eloquent
{
    use Sortable;

    public $sortingParentColumn = 'user_id';

    ...
}

use Sudo520\LaravelSortable\Sortable;

class MyModel extends Eloquent
{
    use Sortable;

    public $startSortingFrom = 0;

    ...
}

MyModel::create([...]); // sort_index 0
MyModel::create([...]); // sort_index 1
MyModel::create([...]); // sort_index 2


/*
    Models

    ['id' => 1, 'sort_index' => 2];
    ['id' => 2, 'sort_index' => 3];
    ['id' => 3, 'sort_index' => 1];
*/

MyModel::pluck('id'); // [1, 2, 3]
MyModel::sorted()->pluck('id'); // [3, 1, 2]


MyModel::swapSort($modelOne, $modelTwo);

$myModel->moveSortIndexDown();
$myModel->moveSortIndexUp();
$myModel->toSortingTop();
$myModel->toSortingBottom();

use Sudo520\LaravelSortable\Sortable;

class MyModel extends Eloquent
{
    use Sortable;

    public $sortIndexColumn = 'order';

    ...
}

$one = $myModel::create([...]); //order 1
$two = $myModel::create([...]); //order 2
$three = $myModel::create([...]); //order 3
$four = $myModel::create([...]); //order 4

$four->update(['order' => 2]);
//$one -> order 1;
//$four -> order 2;
//$two -> order 3;
//$three -> order 4;