You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.');
        }
    },
]);

方法二:创建可复用的自定义验证规则类

如果这个验证逻辑需要在多处使用,推荐使用自定义规则类:

  1. 生成规则类文件:
php artisan make:rule UuidExistsInEitherTable
  1. 编辑生成的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.';
    }
}
  1. 在验证中调用该规则:
use App\Rules\UuidExistsInEitherTable;

$request->validate([
    'uuid' => [new UuidExistsInEitherTable],
]);

内容的提问来源于stack exchange,提问作者Niklas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 12:23:17