duanquan1207 2018-05-29 14:00
浏览 227

将Laravel验证错误作为JSON响应返回

In my RegisterController in Laravel I'm having trouble returning the errors to my front-end. Our application is built as a REST API, so the registration of a new user happens through an AJAX post to the registration route. This works fine if the validation passes, but if the validation fails, no errors are shown. It just redirects to a Laravel homepage. We are not using Blade for the front-end, so it's not possible to get the default validation errors from Blade. The front-end is a ReactJS client that communicates with the back-end through AJAX calls.

How do I get a JSON with the fields that didn't pass validation back to my front-end?

protected function validator(array $data)
{
    return Validator::make($data, [
        'first_name' => 'required|string|max:255',
        'last_name'  => 'required|string|max:255',
        'email'      => 'required|string|email|max:255|unique:users',
        'password'   => 'required|string|min:6|confirmed',
        'birth_year' => 'required|integer|min:4',
        'lat'        => 'required|numeric',
        'lon'        => 'required|numeric',
    ]);        
}
  • 写回答

3条回答 默认 最新

  • duansha8115 2018-05-29 14:17
    关注

    Your code is fine, you can catch the errors because laravel will automatically return a JSON response with a 422 HTTP status.

    So basically in your ajax use the error function, if the validator fails ajax will automatically execute the code you have in your error from ajax.

    For more info on how to properly handle error's for your ajax please take a look at this question. Displaying validation errors in Laravel 5 with React.js and AJAX

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条