Laravel 5.5向Blade视图传参报错:集合实例无[image]属性
问题分析:Laravel Blade中"Property [image] does not exist on this collection instance"错误
嘿,这个问题我太熟悉了!咱们来一步步拆解:
报错根本原因
你在控制器里用了get()方法来查询数据,这个方法返回的是Laravel集合(Collection)——也就是一组模型实例的集合,哪怕数据库里只有一条匹配的记录,它还是会返回一个包含单个元素的集合。
而你在Blade视图里直接写$instrumentUnderEdit->image,这是在尝试从集合对象上获取image属性,但集合本身并没有这个属性(只有单个模型实例才会绑定数据库字段对应的属性),所以就抛出了这个错误。
解决方法
1. 把控制器里的get()改成first()
因为你的查询是根据instruments.id = $id来获取单个仪器信息,完全不需要用get()返回集合,换成first()就能直接拿到单个模型实例:
public function details($id) { $instrument = Instruments::join('revisions', 'revisions.id', '=', 'instruments.revisions_id') ->where([ ['revisions.revision_status', '=', '1'], ['instruments.id', '=', $id], ]) ->orderBy('instruments.name') ->first(); // 这里从get()改成first() $team = Team::join('instruments', 'teams.instruments_id', '=', 'instruments.id') ->join('revisions', 'revisions.id', '=', 'teams.revisions_id') ->where([ ['revisions.revision_status', '=', '1'], ['instruments.id', '=', $id], ]) ->orderBy('instruments.name') ->get(); // 如果team是多条数据,这里可以保留get(),但视图里要循环遍历 return view('details')->with('instrumentUnderEdit', $instrument)->with('teamUnderEdit', $team); }
2. (可选)在Blade视图中增加空值判断
为了避免如果查询不到数据时再次报错,可以给视图加个安全判断:
@if($instrumentUnderEdit) <img style="height: 32px; width: 32px;" src="{{ asset('images/' . $instrumentUnderEdit->image) }}" /> {{ $instrumentUnderEdit->name }} @else <p>暂无仪器信息</p> @endif
关于变量传递的说明
你的变量传递方式是完全没问题的——with()方法可以正确把数据传递到视图,问题根本不在传递环节,而是你传递的是集合而非单个模型实例。
内容的提问来源于stack exchange,提问作者Carol.Kar
相关产品推荐
相关产品推荐

