Laravel Dynamic Position sorting for Backend Restful API

Hello developers.

Today I will show you how to make a sortable column dynamic without Frontend. When you write Restful API and you have a table that must be sort dynamically you can’t do that without Frontend. This problem occurred when you want to do drag and drop functionality over the REST API. If you have many columns you can’t get all columns and can’t do that.

For this problem have a package for doing that. Then I show how to fix this problem:)


Install package through Composer

composer require rutorika/sortable

Sortable Trait

Adds sortable behavior to Eloquent (Laravel) models


Add position field to your model (see below how to change this name):

// schema builder example
public function up()
Schema::create('articles', function (Blueprint $table) {
// ... other fields ...
$table->integer('position'); // Your model must have position field:

Add \Rutorika\Sortable\SortableTrait to your Eloquent model.

class Article extends Model
use \Rutorika\Sortable\SortableTrait;

if you want to use custom column name for position, set $sortableField:

class Article extends Model
use \Rutorika\Sortable\SortableTrait;
protected static $sortableField = 'somefield';

Now you can move your entities with methods moveBefore($entity) and moveAfter($entity) (you dont need to save model after that, it has saved already):

$entity = Article::find(1);

$positionEntity = Article::find(10)


// if $positionEntity->position is 14, then $entity->position is 15 now

Also this trait automatically defines entity position on the create event, so you do not need to add position manually, just create entities as usual:

$article = new Article();
$article->title = $faker->sentence(2);
$article->description = $faker->paragraph();

This entity will be at position entitiesMaximumPosition + 1

To get ordered entities use the sorted scope:

$articles = Article::sorted()->get();

** Note **: Resorting does not take place after a record is deleted. Gaps in positional values do not affect the ordering of your lists. However, if you prefer to prevent gaps you can reposition your models using the deleting event. Something like:

// YourAppServiceProvider

YourModel::deleting(function ($model) {

You need rutorika-sortable >=2.3 to use ->next()

Sortable groups

if you want group entity ordering by field, add to your model

protected static $sortableGroupField = 'fieldName';

now moving and ordering will be encapsulated by this field.

If you want group entity ordering by many fields, use as an array:

protected static $sortableGroupField = ['fieldName1','fieldName2'];

Sortable many to many

Let's assume your database structure is




and you want to order tags for each post

Add position column to the pivot table (you can use any name you want, but position is used by default)


Add \Rutorika\Sortable\BelongsToSortedManyTrait to your Post model and define belongsToSortedMany relation provided by this trait:

class Post extends Model {

use BelongsToSortedManyTrait;

public function tags()
return $this->belongsToSortedMany('\App\Tag');

Note: $this->belongsToSortedMany has different signature then $this->belongsToMany -- the second argument for this method is $orderColumn ('position' by default), next arguments are the same

Attaching tags to post with save/sync/attach methods will set proper position

$post->tags()->save($tag) // or
$post->tags()->attach($tag->id) // or
$post->tags()->sync([$tagId1, $tagId2, /* ...tagIds */])

Getting related model is sorted by position

$post->tags; // ordered by position by default

You can reorder tags for given post

$post->tags()->moveBefore($entityToMove, $whereToMoveEntity); // or
$post->tags()->moveAfter($entityToMove, $whereToMoveEntity);

Many to many demo: (code)

You can also use polymorphic many to many relation with sortable behavour by using the MorphsToSortedManyTrait trait and returning $this->morphToSortedMany() from relation method.

By following the Laravel polymorphic many to many table relation your tables should look like


And your model like

class Post extends Model {    use MorphToSortedManyTrait;    public function tags()
return $this->morphToSortedMany('\App\Tag', 'taggable');

Sortable Controller

Also this package provides \Rutorika\Sortable\SortableController, which handle requests to sort entities


Add the service provider to config/app.php

'providers' => array(
// providers...

publish the config:

php artisan vendor:publish

Add models you need to sort in the config config/sortable.php:

'entities' => array(
'articles' => '\App\Article', // entityNameForUseInRequest => ModelName
// or
'articles' => ['entity' => '\App\Article'],
// or for many to many
'posts' => [
'entity' => '\App\Post',
'relation' => 'tags' // relation name (method name which returns $this->belongsToSortedMany)

Add route to the sort method of the controller:

Route::post('sort', '\Rutorika\Sortable\SortableController@sort');

Now if you post to this route valid data:

Then entity with \Input::get('id') id will be moved relative by entity with \Input::get('positionEntityId') id.

For example, if request data is:


then the article with id 3 will be moved after the article with id 14.

jQuery UI sortable example

Note: Laravel 5 has csrf middleware enabled by default, so you should setup ajax requests:


Template for many to many ordering


You also can read package original documentation in there

Thank you for reading:)

I am iron man

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store