我在我的网站上为用户提供了一个收藏夹列表,他们可以将自己喜欢的房子添加到收藏夹中
进展顺利,但他看不到愿望清单页面,并且出现了这样的错误:
试图获取非对象的属性“图像”
这是我的关系
class Home extends Model
{
protected $guarded = [];
public function favorite()
{
return $this->hasMany(favorite::class,'house_id');
}
}
class favorite extends Model
{
protected $guarded = [];
public function house()
{
return $this->belongsTo(home::class);
}
}
我在控制器中的索引功能:
public function index()
{
$favorite = favorite::where('user_id',auth()->user()->id)->get();
return view('favorite.index',compact('favorite'));
}
我的索引:
@foreach($favorite as $fav)
<tr>
<td>
<a href="property-detail.html"><img src="{{$fav->home->image}}" alt=""
width="100"></a>
</td>
<td><a href="property-detail.html">{{$fav->home->title}}</a></td>
<td>خانه خانواده</td>
<td>اجاره</td>
<td>
<div class="price"><span>{{number_format($fav->home->price)}}</span><strong>تومان</strong>
</div>
</td>
<td>
<a href="#" class="action-button"><i class="fa fa-ban"></i> <span>حذف</span></a>
</td>
</tr>
@endforeach
答案 0 :(得分:0)
您最喜欢的模型没有房屋关系的第一件事就是房屋,当您想要获得房屋价值时,可以使用optional
辅助函数,如下所示:
optional($fav->house)->title
答案 1 :(得分:0)
您正在尝试使用错误的名称访问关系。您使用名称house
定义了关系:
public function house(){
return $this->belongsTo(home::class);
}
因此,您需要使用该名称来访问:
@foreach($favorite as $fav)
<tr>
<td>
<a href="property-detail.html"><img src="{{$fav->house->image}}" alt="" width="100"></a>
</td>
<td><a href="property-detail.html">{{$fav->house->title}}</a></td>
<td>خانه خانواده</td>
<td>اجاره</td>
<td>
<div class="price"><span>{{number_format($fav->house->price)}}</span><strong>تومان</strong>
</div>
</td>
<td>
<a href="#" class="action-button"><i class="fa fa-ban"></i> <span>حذف</span></a>
</td>
</tr>
@endforeach
但是如果house
关系为null,您也会遇到问题。为了避免这种情况,您可以使用@Mohammed Aktaa提出的解决方案:
optional($fav->house)->title