Jagdish Patel
Jagdish Patel

Reputation: 196

Create custom required rule in Laravel validation

My goal is to allow user to select which field is required and which is optional from database.

I have created custom required rule which checks if field is marked as true and is empty then it will fails validation.

It is working fine for required fields i.e. fields which are marked as required. But for other fields which are optional I am getting error like 'The field must be string'. Because it is not set as nullable. If I add nullable then my custom rule is being ignored.

How can I achieve my purpose like if field is not required then it should treat it as nullable.

Below is rule:

'name' => [
    new RequiredRule(),
    'string',
],

Below is RequiredRule:


namespace App\Rules;

use Closure;
use App\Models\RuleTable;
use Illuminate\Contracts\Validation\ValidationRule;

final class RequiredRule implements ValidationRule
{
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $attribute = RuleTable::query()->where('field', $attribute)->first();
        
        if ($attribute->required && empty($value)) {
            $fail("The {$attribute->display_name} field is required.");
        }
    }
}

Upvotes: 0

Views: 215

Answers (2)

Andriy Ivanchenko
Andriy Ivanchenko

Reputation: 101

Laravel 7

use Illuminate\Contracts\Validation\ImplicitRule;

class CustomRule implements ImplicitRule {
}

Upvotes: 0

zlatan
zlatan

Reputation: 4004

For optional fields, you can use sometimes validation:

Run validation checks against a field only if that field is present in the data being validated.

This means, if you don't submit an input, the String validation rule won't be applied to it. You can do it like this:

'name' => [
    'sometimes',
    new RequiredRule(),
    'string',
],

In the example above, the name field will only be validated if it is present in the data that you're submitting.

Upvotes: 1

Related Questions