在 Laravel 中无效后防止重定向到主页

2022-01-22 00:00:00 postman php laravel ajax

我正在使用 Laravel 5.3 开发一个 RESTful API,因此我正在使用我的控制器测试一些功能和请求.我需要做的一件事是在我的数据库中添加字段之前验证我的用户发送的请求,因此,我使用自定义 FormRequest 来验证它.

I'm developing a RESTful API with Laravel 5.3, so I'm testing some functions and request with my controllers. One thing I need to do is validate the request that my user sends before add a field in my database, so, I use a custom FormRequest to validate it.

当我在 Postman 中测试我的 API 并发送无效请求时,响应会将我重定向到主页.阅读文档后,我发现了以下语句

When I tested my API in Postman and send my invalid request, response redirect me to homepage. After reading documentation, I found the following statement

如果验证失败,将生成重定向响应以发送用户回到他们之前的位置.错误也会一闪而过到会话,以便它们可以显示.如果请求是一个 AJAX 请求,一个带有 422 状态码的 HTTP 响应将是返回给用户,包括验证的 JSON 表示错误.

If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

如何防止这种情况发生?还是 Postman 中有 AJAX 模式?有什么建议吗?

How can I prevent this? Or there is a AJAX mode in Postman? Any suggestion?

推荐答案

您的自定义 FormRequest 扩展了 IlluminateFoundationHttpFormRequest.内部是一个执行重定向的函数,称为 response().只需在您的自定义 FormRequest 中覆盖此函数即可更改无效验证的响应方式.

Your custom FormRequest extends IlluminateFoundationHttpFormRequest. Within is a function that performs the redirect called response(). Simply override this function within your custom FormRequest to change how invalid validations are responded to.

namespace AppHttpRequests;

use IlluminateFoundationHttpFormRequest;
use IlluminateHttpJsonResponse;

class CustomFormRequest extends FormRequest
{
    /**
     * Custom Failed Response
     *
     * Overrides the IlluminateFoundationHttpFormRequest
     * response function to stop it from auto redirecting
     * and applies a API custom response format.
     *
     * @param array $errors
     * @return JsonResponse
     */
    public function response(array $errors) {

        // Put whatever response you want here.
        return new JsonResponse([
            'status' => '422',
            'errors' => $errors,
        ], 422);
    }
}

相关文章