Laravel Validator返回错误消息

时间:2017-11-16 15:11:12

标签: php ajax laravel validation

public function search()
{
    if ($this->articleValidator->validateSearch(request())) {
        $response['response'] = TRUE;
        $response['data']['articles'] = $this->articleService->searchArticles(request()->keyword, request()->category, request()->from, request()->to);
        $response['html'] = view('partials/content-administrator-subsystem/articles', $response['data'])->render();
    } else {
        $response['response'] = $this->articleValidator->searchValidationErrors();
    }

    return json_encode($response);
    exit;
}

我在ArticlesPageController中有这个功能。我用axios发送一个POST请求到这个方法。

class ArticleValidator implements ArticleValidatorInterface
{
    protected $searchValidator;

    /**
     * Validates articles search request
     *
     * @param request - Request object
     * @returns true/false if validation succeeded
     */
    public function validateSearch($request)
    {
        $this->searchValidator = Validator::make($request->all(), [
            'category' => 'array|min:1|exists:categories,id',
            'from' => 'date',
            'to' => 'date|after_or_equal:from'
        ]);

        return !$this->searchValidator->fails();
    }

    /**
     * Returns search validation errors
     *
     * @return validation errors or null if everything went well
     */
    public function searchValidationErrors()
    {
        if ($this->searchValidator) {
            print_r($this->searchValidator->errors()->getMessages());
            return $this->searchValidator->errors();
        }

        return null;
    }
}

这是验证员类。

问题是,如果验证器失败,我得到这样的回报:

{ 
    "response": { 
        "to": ["validation.after_or_equal"] 
    } 
}

正如您所看到的,验证规则失败了,问题是,我需要获取实际消息而不是失败的规则。

我知道在正常流程中,我可以return redirect()->withErrors($errors)并且在视图中我会得到一个$ errors数组,但现在,当它是一个AJAX调用时,我无法进行任何重定向。那么如何获取实际消息并将其返回?

1 个答案:

答案 0 :(得分:1)

正如您在此处https://laravel.com/docs/5.5/validation#quick-writing-the-validation-logic所见,当您使用validate()方法并且您的请求是AJAX时,您会在响应中获得JSON格式的错误。您可以在此处查看另一种使用验证程序的方法https://laravel.com/docs/5.5/validation#automatic-redirection

您可能需要检查相应版本的文档,因为随着时间的推移会有轻微的变化,但这应该会给您一个kickstart。