laravel / ideas

Issues board used for Laravel internals discussions.
939 stars 28 forks source link

Adding `when` to unique validation rule #2440

Open ragingdave opened 3 years ago

ragingdave commented 3 years ago

It came across my mind that when setting up requests with validation, I would guess that alot of the time, storing and updating only differ by a few differences. As such, rather than duplicating whole requests to change one thing or extending the store request to alter the rules or such. I would think most of the time the simplest is just to use $this->method() and determine what to do from there.

One rule that uniquely would fit this use case is the unique rule.

For this, something like this is currently needed:

$rule = Rule::unique(Class\Name::class)

if ($this->method() == 'PUT') {
    $rule->ignore($modelToUpdate);
}

Thats a pretty straight forward and verbose thing....but what if we could do so fluently, taking hints from the query builder and use:

Rule::unique(Class\Name::class)
    ->when($this->method() == 'PUT', fn ($rule) => $rule->ignore($modelToUpdate))

Perhaps even in such common cases we could even have:

Rule::unique(Class\Name::class)->whenUpdating(fn ($rule) => $rule->ignore($modelToUpdate))

// OR  specific to the unique class
ignoreWhenUpdating($model) / ignoreWhen($condition , $callback)

Et Voila! Simple, fluent usage of Rules to define multi request type rule checks that are far more readable than previous! Granted the same functionality/customization would be available in any of these variations, just simplified it a bit for this initial post.

If anyone would be interested I would gladly get started on a PR to submit this as a feature, but wanted to gauge interest to see if it was even worth doing.