Laravel 5.5.验证请求重定向/响应 [英] Laravel 5.5. validation request redirect/response

查看:78
本文介绍了Laravel 5.5.验证请求重定向/响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以覆盖验证请求中的某些属性来控制如果验证失败怎么办吗? (我不想在控制器中使用验证)

Can I override some property in validation request to control what happens if validation fails? (I don't want to use validation in controller)

我有用户验证请求:

public function rules()
{
    return [
        'email'                 => 'required|email|max:255|unique:user',
        'name'                  => 'required',
        'password'              => 'required|min:6',
        'password_confirmation' => 'required|min:6|same:password'
    ];
}

当进行AJAX调用以注册方法时,会发生这种情况:

And when AJAX call is made to register method this happens:

public function postRegisterAjax(UserRegistrationValidationRequest $request)
{
    ...
    return $this->responseJson($status, $msg);
}

我需要以某种方式更新$msg,以便我可以通过JS动态返回验证错误消息.

I need to update $msg somehow so that I can return the validation error message dynamically through JS.

我的最终解决方案(在我的自定义表单请求中)

my final solution (in my custom form request)

public function failedValidation(Validator $validator)
{
    if ($validator->fails()) {
        $status = Status::ERROR;
        throw new HttpResponseException(response()->json(["response" => [
            'msg'    => $validator->errors()->all(':message'),
            'status' => $status
        ]]));
    }

    return response()->json(["response" => [
        'msg'    => 'User successfully registered',
        'status' => Status::SUCCESS
    ]]);
}

推荐答案

返回验证错误消息:

Laravel表单请求验证中,如果验证失败,则在AJAX请求的情况下,将返回JSON响应. JSON响应包含所有验证错误.您可以在ajax错误响应中访问它们. (转储您的错误响应,您可以在responseJSON中看到它们.)

In Laravel Form Request Validation, if validation fails, in the case of an AJAX request, a JSON response will be returned. The JSON response holds all validation errors. You can access them in your ajax error response. (dump your error response, you can see them in responseJSON).

如果您想添加其他逻辑/验证并将错误附加到您的error bag,则可以使用验证后挂钩.

If you would like to add additional logic/validation and append errors to your error bag, you can use after-validation-hook.

希望它将对您有帮助.

更新

您可以像下面那样覆盖laravel form request的响应方法,

You can override the laravel form request's response method like the follwing,

public function response(array $errors)
    {
        return response()->json(['status' => $status, "response" => $errors]);
    }

在您的回复中,您将能够以data.response

in your response you would be able to access the errors as data.response

这篇关于Laravel 5.5.验证请求重定向/响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆