使用验证规则(Laravel 验证)检查表 A 或表 B 中是否存在 UUID?

问题描述 投票:0回答:1

在我的 Laravel 应用程序中,我想使用验证规则检查字段

uuid
的值是否存在于表
courses
或表
contingents
中。 UUID 必须出现在两个表之一中才能继续。当我应用以下规则集时,Laravel 要求两个表中都存在 UUID:

$request->validate([
   'uuid' => 'exists:courses,course_id',
   'uuid' => 'exists:contingents,contingent_id
]);

需要某种“微分逻辑”。可以通过一些 if 语句来实现它,但这不是解决问题的一种非常干净的方法,我猜。

如何告诉 Laravel UUID 只需存在于一张表中即可进行验证?

提前致谢。

laravel laravel-9 laravel-validation
1个回答
0
投票
$request->validate([
    'uuid' => [
        'required',
        function ($attribute, $value, $fail) {
            $courseExists = DB::table('courses')->where('course_id', $value)->exists();
            $contingentExists = DB::table('contingents')->where('contingent_id', $value)->exists();

            if (!$courseExists && !$contingentExists) {
                $fail('The :attribute must exist in either the courses or contingents table.');
            }
        },
    ],
]);
© www.soinside.com 2019 - 2024. All rights reserved.