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

Laravel Livewire如何获取Select下拉框分类name和id并存入数据库

现有代码核心问题

  • 未在Livewire组件中声明与下拉框绑定的公共属性 $cateId,wire:model 绑定的变量必须定义为组件公共属性才能正常同步数据
  • Blade模板循环时的临时变量 $item 仅在渲染阶段生效,不会传递到后端组件,$this->$item->name 属于无效取值,后端只能拿到下拉框同步的选中ID值

方案1:保留下拉框传ID逻辑(推荐)

修正后的Livewire控制器代码

// 新增绑定下拉框的公共属性
public $cateId;
public $name;

public function submit()
{
    // 校验选中项合法性
    $this->validate([
        'cateId' => 'required|exists:category,id'
    ]);
    // 根据选中的ID查询对应分类名称
    $selectedCate = \App\Models\Category::findOrFail($this->cateId);
    // 写入新记录
    Category::create([
        'name' => $selectedCate->name,
    ]);
    // 提交后清空选中状态可选
    $this->cateId = '';
}

可选优化Blade模板语义

将原本写在select上的for属性移到label标签上,符合HTML规范:

<label for="cateId">Select a Category</label>
<select id="cateId" class="select2 form-control" wire:model.lazy="cateId">
  <option value="">Select a Category</option>
  @foreach ($categorylist as $item)
   <option value="{{ $item->id }}">{{ $item->name }}</option>
  @endforeach
</select>

方案2:直接下拉框传名称(无需额外查库)

如果不需要用到分类ID,可直接把下拉框的value设为分类名称简化逻辑:

修正后的Blade模板

<label for="cateName">Select a Category</label>
<select id="cateName" class="select2 form-control" wire:model.lazy="cateName">
  <option value="">Select a Category</option>
  @foreach ($categorylist as $item)
   <option value="{{ $item->name }}">{{ $item->name }}</option>
  @endforeach
</select>

修正后的Livewire控制器代码

public $cateName;

public function submit()
{
    $this->validate([
        'cateName' => 'required|string'
    ]);
    Category::create([
        'name' => $this->cateName,
    ]);
    $this->cateName = '';
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:48:01