【发布时间】:2018-04-30 04:38:31
【问题描述】:
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 调用时,我无法进行任何重定向。那么如何获取实际消息并将其返回?
【问题讨论】:
-
您是否尝试返回
$this->searchValidator->messages(); -
你意识到你在
searchValidationErrors()里面有一个print_r()吗? -
如果您删除
print_r并返回$this->searchValidator->messages()而不是$this->searchValidator->errors()您应该会得到想要的结果。 -
print_r 用于调试目的,我按照你说的做了所有更改,但结果相同
-
查看您的
resources/lang/en/validation.php语言文件。after_or_equal有条目吗?
标签: php ajax laravel validation