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

Laravel框架Validator验证失败后Blade不显示错误信息如何修复

问题原因

  • 手动创建Validator实例后没有处理验证失败逻辑,错误信息没有闪存到session,前端无法读取
  • 表单激活复选框字段名拼写错误,和控制器验证规则的字段名不匹配

修复步骤

1. 修改Controller验证逻辑

推荐直接使用$request->validate()方法,该方法验证失败时会自动重定向到上一页,且自动把错误信息和用户输入闪存到session:

use Validator;
public function insert(Request $request)
{
    $data = $request->validate([
        'title' => 'required',
        'name' => 'required|alpha_num',
        'activation' => 'nullable',
        'cachable' => 'nullable'
    ]);

    $wallet = new Wallet();
    $wallet->title = $data['title'];
    $wallet->name = $data['name'];
    $wallet->is_active = !empty($data['activation']) ? 1 : 0;
    $wallet->is_cachable = !empty($data['cachable']) ? 1 : 0;

    $wallet->save();
    
    return redirect(url('admin/wallets/index'));
}

如果你要保留Validator::make的写法,需要手动添加验证失败的跳转逻辑:

$validator = Validator::make($request->all(),[
    'title' => 'required',
    'name' => 'required|alpha_num',
    'activation' => 'nullable',
    'cachable' => 'nullable'
]);
if ($validator->fails()) {
    return redirect()->back()->withErrors($validator)->withInput();
}
$data = $validator->validated();

2. 修复表单字段拼写错误

把表单中激活复选框的name属性从activaton修正为activation,和控制器验证规则的字段名保持一致:

<input class="form-check-input" type="checkbox" name="activation" value="active" id="activationStatus">

可选优化:保留用户上次输入

给表单字段添加old()辅助函数,验证失败跳转回来后会保留用户之前填写的内容:

<input type="text" id="title-shop" name="title" class="form-control" value="{{ old('title') }}" autofocus>
<input type="text" id="title-shop" name="name" class="form-control" value="{{ old('name') }}" autofocus>
<input class="form-check-input" type="checkbox" name="cachable" value="cashable" id="cacheStatus" {{ old('cachable') ? 'checked' : '' }}>
<input class="form-check-input" type="checkbox" name="activation" value="active" id="activationStatus" {{ old('activation') ? 'checked' : '' }}>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 00:51:01