Skander Chouba
Skander Chouba

Reputation: 25

Trying to get property of non-object Laravel 5.5

I'm trying to echo out the name of the user in my article and I'm getting the

ErrorException: Trying to get property of non-object.

My codes:

Offer Model

class Offer extends Model
{
    public function countries()
    {
        return $this->belongsTo(Country::class, 'country_id');    
    }
}

Country Model

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

when Idd($offer->first()->countries) the result is null.

Upvotes: 0

Views: 6296

Answers (2)

Ren
Ren

Reputation: 21

class Offer extends Model
{
    // try change countries to country, because it's one to one relation.
    public function country()
    {
        return $this->belongsTo(Country::class);    
    }
}

then use optional when echo a relation

{{ optional($offer->country)->name }}

The optional function accepts any argument and allows you to access properties or call methods on that object. If the given object is null, properties and methods will simply return null instead of causing an error:

Upvotes: 1

Amit Gupta
Amit Gupta

Reputation: 2806

You need to add foreach loop in your blade file like below:

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

Upvotes: 0

Related Questions