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

Laravel 5.5结合Laravel Collective表单验证后回显旧值的实现问询

解决Laravel Collective表单验证失败后旧值不回显的问题

嘿,这问题我之前也踩过坑!你现在的代码里,Form::text的第二个参数传的是null,这就是旧值回显不了的核心原因——Laravel Collective的表单助手不会自动帮你填充旧值,得咱们手动指定才行。

只需要把表单控件的默认值改成old($question->title)就搞定了,old()方法会在验证失败时自动取出用户之前输入的内容,第一次加载页面或者验证通过时则返回null,完美兼容两种场景。

修改后的完整代码如下:

<div class="@if ($errors->has($question->title)) has-error @endif">
    {!! Form::label($question->title, $question->title) !!}
    {!! Form::text($question->title, old($question->title), ['class' => 'form-control']) !!}
    @if ($errors->has($question->title))
        <p class="help-block">{{ $errors->first($question->title) }}</p>
    @endif
</div>

顺便补充个小知识点:如果是其他类型的表单控件,比如textarea、select或者checkbox,也是同样的逻辑——把默认值参数替换成old()对应的字段名就行。比如Form::textarea的写法就是:

{!! Form::textarea($question->title, old($question->title), ['class' => 'form-control']) !!}

这样调整之后,当表单验证失败跳转回页面时,用户之前输入的内容就会自动回显在对应的输入框里啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:15:20