Php Laravel 5更改表单请求验证行为失败
我有一个表单请求来验证注册数据。该应用程序是一个移动API,我希望该类在验证失败时返回格式化的JSON,而不是默认情况下返回格式化的JSON(重定向) 我尝试从Php Laravel 5更改表单请求验证行为失败,php,json,api,laravel,laravel-5,Php,Json,Api,Laravel,Laravel 5,我有一个表单请求来验证注册数据。该应用程序是一个移动API,我希望该类在验证失败时返回格式化的JSON,而不是默认情况下返回格式化的JSON(重定向) 我尝试从illumb\Foundation\Http\FormRequest类重写方法failedValidation。但这似乎不起作用。有什么想法吗 代码: 通过查看illighted\Foundation\Http\FormRequest中的以下函数,Laravel似乎处理得很好 /** * Get the proper f
illumb\Foundation\Http\FormRequest
类重写方法failedValidation
。但这似乎不起作用。有什么想法吗
代码:
通过查看illighted\Foundation\Http\FormRequest
中的以下函数,Laravel似乎处理得很好
/**
* Get the proper failed validation response for the request.
*
* @param array $errors
* @return \Symfony\Component\HttpFoundation\Response
*/
public function response(array $errors)
{
if ($this->ajax() || $this->wantsJson())
{
return new JsonResponse($errors, 422);
}
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
根据下面lightlight\Http\Request
中的wantsJson
函数,您必须显式地查找JSON
响应
/**
* Determine if the current request is asking for JSON in return.
*
* @return bool
*/
public function wantsJson()
{
$acceptable = $this->getAcceptableContentTypes();
return isset($acceptable[0]) && $acceptable[0] == 'application/json';
}
这是我的解决方案,在我这方面效果很好。我在请求代码下面添加了函数:
public function response(array $errors)
{
if ($this->ajax() || $this->wantsJson())
{
return Response::json($errors);
}
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
laravel能够很好地处理响应函数。如果您请求json或ajax,它将自动返回。无需重写任何函数。只要你加上
Accept: application/json
在表单标题中。Laravel将以相同的URL和JSON格式返回响应。只需在您的请求中添加以下函数:
use Response;
public function response(array $errors)
{
return Response::json($errors);
}
请发布您的代码供人们检查。我猜您是通过AJAX调用API的吧?可以强制API调用从API中获取JSON吗?在jQuery中,它看起来像:$.getJSON。
use Response;
public function response(array $errors)
{
return Response::json($errors);
}