【问题标题】:How to catch validation failure with laravel when using form requests使用表单请求时如何使用 laravel 捕获验证失败
【发布时间】:2016-04-27 15:54:48
【问题描述】:

我正在使用带有 laravel 5.2 的 formrequest 文件来检查输入。我正在使用 jquery 的 $.post 函数调用此表单。在我的控制台中,它返回 422 Unprocessable Entity 我怀疑它来自响应,因为我没有将其格式化为 json。一种做法is this

我想知道如何从我的表单请求中调用,将输出消息更改为 json 的方法。

谢谢!

更新 1

JQuery 看起来像这样:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('input[name="csrf-token"]').val()
    }
});

$("#changePassword").on('click', function(e){
    e.preventDefault();

    var data = {};
    data.name = $("input[name='name']").val();
    data.surname = $("input[name='surname']").val();
    data._token = $('input[name="_token"]').val();

    $.post('url',data).done(function(data){
        $(".message").empty().html("Done!");
    }).fail(
        function(response, status){

        }
    );
});

【问题讨论】:

  • 你能把代码发给你$.post部分吗?

标签: php jquery json laravel


【解决方案1】:

在您的请求类中覆盖响应方法,如下所示

    /**
     * Get the proper failed validation response for the request.
     *
     * @param  array  $errors
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function response(array $errors)
    {
        return Response::json([
            'error' => [
                'message' => $errors,
            ]
        ]);
    }

【讨论】:

  • 正确的方法我最终将其实现为:return response()->json([]);
猜你喜欢
  • 2018-06-15
  • 2019-10-19
  • 2016-10-21
  • 2021-02-22
  • 2017-01-22
  • 2019-06-14
  • 2015-08-12
  • 1970-01-01
  • 2018-06-16
相关资源
最近更新 更多