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

Laravel表单更新时如何保留Select选项的旧值?

在Laravel中更新表单时让Select选项保留旧值的解决方法

你的代码问题出在给<select>标签设置了value属性——HTML里的下拉选择框,选中状态是通过给对应的<option>标签添加selected属性实现的,不是给select本身加value。

下面是两种可行的修正方案:

1. 基础编辑场景(仅展示模型数据)

如果只是编辑现有项目,直接对比模型的slug值给对应option加selected:

<select class="form-select" name="slug" id="slug">
    <option value="" {{ ($project->slug ?? '') === '' ? 'selected' : '' }}>Select Category</option>
    <option value="commercial" {{ ($project->slug ?? '') === 'commercial' ? 'selected' : '' }}>commercial</option>
</select>

2. 兼顾表单验证失败回显的完善方案

如果表单提交后验证失败,需要保留用户之前选的值,用Laravel的old()函数更合适——它会优先取session中存储的提交值,没有的话再用模型的默认值:

<select class="form-select" name="slug" id="slug">
    <option value="" {{ old('slug', $project->slug ?? '') === '' ? 'selected' : '' }}>Select Category</option>
    <option value="commercial" {{ old('slug', $project->slug ?? '') === 'commercial' ? 'selected' : '' }}>commercial</option>
</select>

更灵活的循环写法(适合多选项场景)

如果你的分类选项是从数据库或数组来的,推荐用循环生成option,避免手动重复代码:

// 控制器里定义分类数组(或从数据库查询)
$categories = [
    '' => 'Select Category',
    'commercial' => 'commercial',
    // 可添加更多分类
];
<select class="form-select" name="slug" id="slug">
    @foreach($categories as $value => $label)
        <option value="{{ $value }}" {{ old('slug', $project->slug ?? '') === $value ? 'selected' : '' }}>
            {{ $label }}
        </option>
    @endforeach
</select>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 10:42:12