我试图在文章中回应用户的名字而我正在
ErrorException: Trying to get property of non-object.
我的代码:
优惠模式
class Offer extends Model
{
public function countries()
{
return $this->belongsTo(Country::class, 'country_id');
}
}
国家/地区模型
class Country extends Model
{
public function offers()
{
return $this->hasMany(Offer::class);
}
}
index.blade
{{ $offer->countries->name }}
OfferController
public function index()
{
$offers = Offer::latest()->paginate(5);
return view('admin.offers.index', compact('offers'))
当我dd($offer->first()->countries)
时,结果为空。
答案 0 :(得分:0)
您需要在刀片文件中添加foreach循环,如下所示:
@foreach($offers as $offer)
{{ $offer->countries->name }}
@endforeach
答案 1 :(得分:0)
class Offer extends Model
{
// try change countries to country, because it's one to one relation.
public function country()
{
return $this->belongsTo(Country::class);
}
}
然后在回显关系时使用可选
{{ optional($offer->country)->name }}
可选函数接受任何参数,并允许您访问该对象的属性或调用方法。如果给定对象为null,则属性和方法将仅返回null而不是导致错误: