You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel表单验证失败时重定向至Web路由问题求助

Laravel 10 Form Request验证失败返回JSON而非重定向的解决方案

在Laravel 10.30.1中使用Form Request处理API验证时,出现验证失败后重定向至Web首页的问题,而手动创建Validator可正常返回JSON错误,以下是针对性解决方法:

解决步骤

1. 确保请求携带Accept头

Laravel默认通过请求头的Accept字段判断响应格式。发送API请求时,必须添加:

Accept: application/json

若缺少该头,Laravel会将请求判定为Web请求,触发验证失败后的重定向逻辑。

2. 重写Form Request的验证失败处理逻辑

如果无法保证前端请求都携带正确的Accept头,可直接在EmployeeUpdateRequest中强制返回JSON错误:

<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class EmployeeUpdateRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'cpf' => 'required|size:11|unique:employees,cpf,' . $this->employee->id,
        ];
    }

    /**
     * 覆盖验证失败默认逻辑,返回JSON错误
     */
    protected function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(
            response()->json(['errors' => $validator->errors()], 400)
        );
    }
}

注:规则中添加了,' . $this->employee->id,避免更新时因当前员工自身CPF存在而触发unique验证失败。

3. 确保API路由应用api中间件

检查路由定义,确保API路由组使用api中间件组,该中间件默认包含API请求的必要配置(如CSRF豁免、请求头识别):

<?php

use App\Http\Controllers\EmployeeController;
use Illuminate\Support\Facades\Route;

Route::prefix('v1')->middleware('api')->group(function () {
    Route::resource('employees', EmployeeController::class)
        ->only(['store', 'index', 'update']);
});

内容的提问来源于stack exchange,提问作者Thiago Maciel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 23:30:55