【问题标题】:How to pass a variable to custom validator如何将变量传递给自定义验证器
【发布时间】:2017-05-12 18:29:06
【问题描述】:

我创建了一个驻留在 AppServiceProvider 中的自定义验证器。 boot 方法包含一个 DB 方法,该方法应接受传递给验证器的第一个参数作为表名。当我手动填写表名时,它可以工作,但是当我传递第一个参数时,我遇到了这个错误:

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

【问题讨论】:

  • 你不能只设置“uniqueForStore:users”吗?
  • 谢谢@PatrykWoziński。有用。如果您添加答案,我可以接受。
  • 好的。谢谢。 :)

标签: php laravel laravel-5.2


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多