【问题标题】:Laravel withValidator() not working as expectedLaravel withValidator() 没有按预期工作
【发布时间】:2018-08-27 23:41:10
【问题描述】:

我有这个包含规则和 withValidator 作为第二层验证的表单请求。

注意:我知道让它在规则上是唯一的会抑制这个例子的需要,但我需要在这里做进一步的验证。

public function rules(Request $request) {
        return [
            "name"              => "required|max:191",
            "begin_date"        => "required|after_or_equal:today|date_format:d-m-Y",
            "end_date"          => "required|after:begin_date|date_format:d-m-Y",
        ];
}

public function withValidator($factory) {
        $result = User::where('name', $this->name)->get();
        if (!$result->isEmpty()) {
            $factory->errors()->add('User', 'Something wrong with this guy');
        }
        return $factory;
}

我很肯定它进入了if,因为我之前已经放置了一个 dd 来检查它是否在里面。但是,它在 Controller 上继续使用此方法,我不希望它这样做。

public function justATest(UserRequest $request) { 
       dd("HI");
}

【问题讨论】:

  • 但是你没有调用 $this->validate()
  • 无需在表单请求中调用该方法,我刚刚发现下面的答案中缺少什么。我是个白痴

标签: php laravel


【解决方案1】:

我也遇到过这个问题。 我将 withValidator 更改为:

public function withValidator($validator)
{
    if (!$validator->fails()) {
        $validator->after(function ($validator) {
            if (Cache::has($this->mobile)) {
                if (Cache::get($this->mobile) != $this->code) {
                    $validator->errors()->add('code', 'code is incorrect!');
                } else {
                    $this->user = User::where('mobile', $this->mobile)->first();
                }
            } else {
                $validator->errors()->add('code', 'code not found!');
            }
        });
    }

【讨论】:

    【解决方案2】:

    我是个白痴,没有阅读完整的文档。

    需要用 after 函数指定,像这样:

    public function withValidator($factory) {
            $result = User::where('name', $this->name)->get();
            $factory->after(function ($factory) use ($result) {
                if (!$result->isEmpty()) {
                    $factory->errors()->add('User', 'Something wrong with this guy');
                }
            });
            return $factory;
    }
    

    【讨论】:

    • 对我来说 withValidator(...) 甚至没有被调用过,也许添加到文档的链接。
    猜你喜欢
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 2015-10-30
    • 2015-11-09
    相关资源
    最近更新 更多