gurgentil / laravel-eloquent-sequencer

A package that allows you to create and manage sequences on Eloquent models.
MIT License
156 stars 13 forks source link

Set to max or min vs out of bounds. #8

Closed dillingham closed 4 years ago

dillingham commented 4 years ago

Great package! Thanks for publishing.

I am using it with Nova and have a order column as a text field. Makes it very simple to reorder models this way.

Ideally, if a user entered 100.. And there were only 10 records.. It would default to 10 automatically.

Similarly, if a user entered -10.. It would default to 1 automatically.

Just food for thought :)

dillingham commented 4 years ago

I might write a blog post about using this with Nova for ordering / sortables. Just would need min / max automatic or figure some validation 🤔

gurgentil commented 4 years ago

Hi there. Thank you so much for your feedback!

I would rather keep the exception to avoid inconsistency between user input and the actual value stored in the database.

One quick solution if you would like to try going with the validation approach: Sequenceable exposes two methods that you could use to get the max value in a sequence: getLastSequenceValue() and getNextSequenceValue(). So something like "max:{$task->getNextSequenceValue()}" should do it.

Please, let me know if this works for you.

dillingham commented 4 years ago

@gurgentil thanks! Almost worked it out like so:

static::saving(function($model) {
    if($model->isDirty('order')) {
        $next = $model->getLastSequenceValue();
        if($model->order > $next) {
            $model->order = $next;
        } elseif($model->order <= 0) {
            $model->order = 1;
        }
    }
});

But the exception prevents me from going with this solution.

Made a PR (https://github.com/gurgentil/laravel-eloquent-sequencer/pull/12) for turning it off but keeping it the default behavior.