如何将变量传递给自定义验证器

How to pass a variable to custom validator

我创建了一个驻留在 AppServiceProvider 中的自定义验证器。 boot 方法包含一个 DB 方法,它应该接受传递给验证器的第一个参数作为 table 名称。当我手动填写 table 名称时,它有效但是当传递第一个参数时,我 运行 进入此错误:

QueryException in Connection.php line 729:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'server1.{users}' 
doesn't exist (SQL: select count(*) as aggregate from `{users}` where `email` = 
mail@mail.com and `STORE_ID` = 2)

这是我的服务提供商代码:

public function boot()
{
  Validator::extend('uniqueForStore', function ($attribute, $value, $parameters, $validator) {
      $count = DB::table($parameters[0])->where($attribute, $value)->where('STORE_ID', config('constants.STORE_ID'))->count();
      return $count === 0;
  });
}

这就是问题所在:

DB::table($parameters[0])

这是我的注册用户表单请求代码:

public function rules()
{
    return [
        'first_name' => 'required',
        'last_name' => 'required',
        'email' => "uniqueForStore:{users}",
        'password' => 'required|min:6'
    ];
}

如下设置您的验证规则 - 只需删除唯一值(用户)的括号:

public function rules()
{
    return [
        'first_name' => 'required',
        'last_name' => 'required',
        'email' => "uniqueForStore:users",
        'password' => 'required|min:6'
    ];
}