Omar
Omar

Reputation: 643

Laravel validation exists in this table OR that table

I need to validate the existence of an API request parameter but check it in one of two tables, users and teachers something like this

$rules = ['apiToken' => 'required|string|min:70|exists:users,api_token ((OR)) exists:teachers,api_token']

is there a way to achieve this using Laravel validator?

Upvotes: 5

Views: 3036

Answers (1)

Rwd
Rwd

Reputation: 35180

For something like this you will probably need to use custom validation:

$rules = [
    'apiToken' => [
        'required', 'string', 'min:70', function ($attribute, $value, $fail) {

            if (!DB::table('users')->where('api_token', $value)->exists() || !DB::table('teachers')->where('api_token', $value)->exists()) {
                return $fail("The provided $attribute is not valid.");
            }
        }
    ]
];

You can change the returned error message by editing the text passed to the $fail function.

Upvotes: 5

Related Questions