TIL: Running a validation rule when the value when the value is empty
For a weird usecase I needed a custom validation rule in Laravel to run when the value for the checked field was empty.
This is when I learned that Laravel won't run a validation rule when the value of the field is empty.
After a bit of digging I found this fixed by simply marking your validation rule as implicit:
class MyCustomRule implements ValidationRule { public bool $implicit = true; public function validate(string $attribute, mixed $value, Closure $fail): void { // Now your rule will alwasy run! } }
This is something that is pretty easy once you know it, but for me it took quite some Googeling so I hope I save someone some time writing this down!