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

Laravel中如何在多选Select2中显示中间表(pivot)值?

在Laravel多选Select2中显示中间表的service_id值

解决方法

直接将视图代码中的pivot_should_be_here替换为services->pluck('id')即可,修改后的完整代码如下:

@foreach ($service as $item)
     <option value="{{ $item->id }}"
        {{ in_array($item->id, $appointment->services->pluck('id') ?: []) ? 'selected' : '' }}>
        {{ $item->name }}</option>
@endforeach

原理说明

  • 控制器中通过with('services')预加载了预约关联的服务集合,$appointment->services就是这个关联集合。
  • pluck('id')方法会从集合中提取所有服务的ID,生成纯ID数组,刚好适配in_array的判断逻辑,自动选中中间表中已关联的服务。

可选优化(避免空值报错)

如果存在$appointment为空的场景,可增加空值判断防止报错:

@foreach ($service as $item)
     <option value="{{ $item->id }}"
        {{ isset($appointment) && in_array($item->id, $appointment->services->pluck('id')) ? 'selected' : '' }}>
        {{ $item->name }}</option>
@endforeach

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:50:38