Laravel验证规则:如何校验UUID存在于两个数据表之一?
Laravel验证:UUID存在于任意一个表即可通过验证
你当前的写法存在两个问题:一是重复定义uuid字段的验证规则,后定义的规则会覆盖前一个;二是exists规则默认要求字段必须满足该条件,所以即使不覆盖,也会要求UUID同时存在于两个表中,和你的需求不符。
下面提供两种简洁的实现方式:
方法一:使用验证回调函数
直接通过闭包实现“或”逻辑,无需额外创建文件:
$request->validate([ 'uuid' => function ($attribute, $value, $fail) { $inCourses = \DB::table('courses')->where('course_id', $value)->exists(); $inContingents = \DB::table('contingents')->where('contingent_id', $value)->exists(); if (!$inCourses && !$inContingents) { $fail('The :attribute must exist in either courses or contingents.'); } }, ]);
方法二:创建可复用的自定义验证规则类
如果这个验证逻辑需要在多处使用,推荐使用自定义规则类:
- 生成规则类文件:
php artisan make:rule UuidExistsInEitherTable
- 编辑生成的
app/Rules/UuidExistsInEitherTable.php,实现验证逻辑:
<?php namespace App\Rules; use Illuminate\Contracts\Validation\Rule; use Illuminate\Support\Facades\DB; class UuidExistsInEitherTable implements Rule { /** * 判断验证是否通过 * * @param string $attribute * @param mixed $value * @return bool */ public function passes($attribute, $value) { return DB::table('courses')->where('course_id', $value)->exists() || DB::table('contingents')->where('contingent_id', $value)->exists(); } /** * 获取验证错误消息 * * @return string */ public function message() { return 'The :attribute must exist in either courses or contingents.'; } }
- 在验证中调用该规则:
use App\Rules\UuidExistsInEitherTable; $request->validate([ 'uuid' => [new UuidExistsInEitherTable], ]);
内容的提问来源于stack exchange,提问作者Niklas
相关产品推荐
相关产品推荐

