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并发送无效请求时,响应将我重定向到主页.在阅读文档之后,我发现了以下语句

如果验证失败,将生成重定向响应以发送

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

推荐答案

Your custom FormRequest extends Illuminate\Foundation\Http\FormRequest. 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 App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\JsonResponse;

class CustomFormRequest extends FormRequest
{
    /**
     * Custom Failed Response
     *
     * Overrides the Illuminate\Foundation\Http\FormRequest
     * 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);
    }
}

Laravel相关问答推荐

try 编写一个函数,如果产品存在,则无法删除特定类别

Inertia React中的错误文件上传更新

如何在使用Docker容器部署Laravel 8、9、10时处理SIGTERM信号,特别是与调度程序和工作进程相关的问题?

按回车键时如何防止此功能运行?

Laravel 获取具有多对多关系的中间表数据

1 子编译中的警告(使用'stats.children:true'和'--stats-children'了解更多详细信息)

Laravel - 将变量从中间件传递到控制器/路由

路由中间的可选参数

Laravel 5.3 - 将多个文件附加到 Mailables

路由模型绑定不起作用

向 Docker 上的 Artisan 推荐方式

Laravel 5 - 为包创建 Artisan 命令

日期验证 - 如何本地化/翻译字符串今天和明天

WhereHas Laravel 中的关系计数条件是什么

Laravel Mix 生成字体到另一个目录

Laravel - DecryptException:'MAC 无效'

Laravel 5 - 判断日期是否是今天

搜索结果分页 laravel 5.3

如何从 laravel 5.1 中数据库表的 created_at 属性中 Select 年份和月份?

phpunit 命令不适用于 Windows 7 上的 laravel 4