Create Model Sequences With the Eloquent Sequencer Package

News

June 25th, 2020

laravel-earmark.png

Eloquent Sequencer is a package by Gustavo R. Gentil for automatically sequencing your models when adding new records. This package makes it trivial to rearrange things like todos, cards, or lists of models.

Here’s an example from the readme demonstrating a task list that has many Task models:

use Gurgentil\LaravelEloquentSequencer\Traits\Sequenceable;
use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    use Sequenceable;

    protected static $fillable = [
        'position',
    ];

    protected static $sequenceableKeys = [
        'task_list_id',
    ];

    public function taskList()
    {
        return $this->belongsTo(TaskList::class);
    }
}

Let’s say that you have a drag and drop interface for reordering tasks. You could call the following methods, and this package will automatically rearrange the sequence of tasks:

// Other items in the sequence will be rearranged
$task->update(['position' => 4]);

// Remaining tasks will be rearranged after removing a task
$task->delete();

Finally, you’d use the following method to get the sequenced list of tasks:

$tasks = Task::sequenced()->get();

Learn More

You can learn more about this package, get full installation instructions, and view the source code on GitHub at gurgentil/laravel-eloquent-sequencer.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.