试图获得非对象Laravel 5.5的属性

问题描述 投票:0回答:2

我试图在我的文章中回应用户的名字而我正在接受

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'))

当Idd($offer->first()->countries)结果为null时。

php laravel laravel-5 laravel-5.5
2个回答
0
投票

您需要在刀片文件中添加foreach循环,如下所示:

@foreach($offers as $offer) 
{{ $offer->countries->name }} 
@endforeach    

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而不是导致错误:

© www.soinside.com 2019 - 2024. All rights reserved.