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

使用Livewire切换select选项时出现Attempt to read property "id" on array错误

问题原因

切换select选项触发Livewire组件更新时,公共属性$dominios会经历序列化-反序列化过程。Eloquent集合经过这个过程后会转为普通数组,模板遍历$dominios时,$d变成了数组而非模型对象,用->访问属性就会抛出Attempt to read property "id" on array错误。

解决方案

推荐两种可靠的解决方式:

方式一:将$dominios移到render方法中传递

把$dominios从公共属性改为在render方法里通过视图传递,每次组件更新都会重新查询数据库获取新鲜的Eloquent集合,彻底规避序列化问题:

class Software extends Component {
    public $dominio_id; 

    public function mount() {
        $this->dominio_id = 1;
        // 其他初始化逻辑
    }

    public function render() {
        return view('livewire.software', [
            'dominios' => Dominio::orderBy('name')->get()
        ]);
    }
}

模板代码无需修改,可正常遍历$dominios。

方式二:利用Livewire钩子重新加载$dominios

如果必须保留$dominios作为公共属性,可在组件的hydrate钩子中重新查询数据,确保每次组件更新后$dominios都是Eloquent集合:

class Software extends Component {
    public $dominio_id, $dominios; 

    public function mount() {
        $this->dominios = Dominio::orderBy('name')->get();
        $this->dominio_id = 1;
        // 其他初始化逻辑
    }

    public function hydrate() {
        // 每次组件刷新后重新加载数据
        $this->dominios = Dominio::orderBy('name')->get();
    }
}

临时兼容方案(不推荐)

仅作临时测试用,在模板中兼容数组与对象的访问方式,但无法从根源解决问题:

<select wire:model="dominio_id">
    @foreach ($dominios as $d)
        <option value="{{ is_array($d) ? $d['id'] : $d->id }}">{{ is_array($d) ? $d['path'] : $d->path }}</option>
    @endforeach
</select>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 11:42:36