且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-02 10:25:22

您的自定义 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);
    }
}