Skip to main content
Back to packages
289 GitHub stars

boxfrommars/rutorika-sortable

View on GitHub

Description

Adds sortable behavior to Laravel Eloquent models

dd 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)
 
$entity->moveAfter($positionEntity);
 
// 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();
$article->save();

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) {
$model->next()->decrement('position');
});

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

Recent Courses on Laravel Daily

Laravel 13 Starter Kit Teams and Customizations

10 lessons
33 min

How to Build Laravel 13 API From Scratch

30 lessons
1 h 23 min

How to Structure Laravel 13 Projects

16 lessons
1 h 32 min read

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.