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

Laravel 5.5:使用required验证规则时为何会发生重定向?

为什么Laravel表单使用required验证规则时会出现重定向?

嘿,这个问题其实是Laravel表单验证的默认机制导致的,我来给你拆解清楚:

核心原因:Laravel验证失败的默认行为

当你使用表单请求(Form Request)(也就是你这里的InboxRequest)进行验证时,一旦验证规则不满足(比如receiver字段为空触发了required规则),Laravel框架会自动执行以下操作:

  • 把验证错误信息存入Session
  • 保留用户提交的旧输入数据(这就是你表单里old('receiver')能生效的原因)
  • 重定向回用户提交表单的页面(也就是compose路由对应的GET页面)

这是Laravel为了提升用户体验设计的默认逻辑——让用户回到表单页面,看到错误提示后修正输入,而不是直接返回一个生硬的错误页面。

如何验证这个逻辑?

你可以在表单页面添加错误提示代码,就能看到重定向后的反馈:

<form role="form" class="form-horizontal" action="{{ route('compose') }}" method="POST">
    {{ csrf_field() }}
    <label class="col-lg-2 control-label">To</label>
    <input type="text" placeholder="" id="inputEmail1" class="form-control" name="receiver" value="{{old('receiver')}}">
    <!-- 添加错误提示 -->
    @if ($errors->has('receiver'))
        <span class="text-danger mt-2 d-block">{{ $errors->first('receiver') }}</span>
    @endif
    
    <!-- 其他表单字段 -->
    <label class="col-lg-2 control-label">From</label>
    <input type="text" placeholder="" id="cc" class="form-control" name="sender" value="{{ Auth::user()->email }}" disabled="">
    <input type="text" placeholder="" id="inputPassword1" class="form-control" name="subject" value="{{old('subject')}}">
    <button class="btn btn-success" type="submit">Send</button>
</form>

现在你提交空的receiver字段,重定向回来后就能看到The receiver field is required.的错误提示了。

如果想修改默认的重定向行为?

如果你不想要重定向(比如这是一个AJAX请求),可以在InboxRequest类中重写failedValidation方法来自定义响应:

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;

protected function failedValidation(Validator $validator)
{
    // 判断是否是AJAX请求
    if ($this->wantsJson()) {
        $response = response()->json([
            'message' => '表单验证失败',
            'errors' => $validator->errors()
        ], 422);
        
        throw new ValidationException($validator, $response);
    }
    
    // 非AJAX请求保留默认重定向
    parent::failedValidation($validator);
}

如果想自定义重定向的URL,可以在InboxRequest中添加redirectTo方法:

protected function redirectTo()
{
    // 替换成你想要重定向的路由
    return route('your-custom-route');
}

内容的提问来源于stack exchange,提问作者Andreas Hunter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:45:08