Home > Blockchain >  How to ignore field itself while creating rule for two different DB table
How to ignore field itself while creating rule for two different DB table

Time:09-12

I have a form and getting input values. One of the input field is email. I need to check that email is unique in two different table but need to allow the value itself in both table. Tried almost all combinations, but couldn't sort it out.

$rules = [
    'email' => "required|unique:admins|unique:vendors,email,$id",
];

The code above works but gives warning that Email has already been taken. But when I use one table only it works as expected. Maybe someone could help me with that, would be highly appreciated.

CodePudding user response:

That seems a good use case for Custom Validation Rules using Closures. Basically, instead of using a bunch of unique rules, you'll simply have a function (closure) where you do your validation logic that decides whether to accept or decline the input.

$rules = [
    /** added "email" rule to tell Laravel that we expect an email address */
    'email' => ['required', 'email', function (string $attribute, string $value, Closure $fail) {
        /** a function that checks whether an "email" exists in a "table" or not */
        $existsInTableFN = fn(string $table): bool => DB::table($table)->where($attribute, $value)->exists();

        /**
         * the below condition means that the validation will FAIL
         * if the "email" is found in one table but doesn't exist in the other
         */
        if ($existsInTableFN('admins') !== $existsInTableFN('vendors'))
            $fail('Email address already taken.'); /** laravel will take care of the rest if the above condition is met */
    }]
];

Summary:

the above closure rule will only accept an email if:

  1. it doesn't exist in both tables
  2. OR does exist in both of them

In other words, the closure rule will fail:

  • if it finds the submitted email in one table
  • but it doesn't find it (the submitted email) in the other table
  • Related