Laravel validation exists in this table OR that table

时间:2019-04-08 13:35:49

标签: laravel

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?

1 个答案:

答案 0 :(得分:1)

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.