Tom Kur
Tom Kur

Reputation: 2398

hasOne() not returning relationships because of method name

I am using laravel 5.3, I have listings table with hasOne relationship to cities table.

public function city()
{
    return $this->hasOne('App\City', 'id', 'city_id');
}

on my view

{{$listing->city->name}}

this cause error

Trying to get property of non-object

But when I change the method name to other than city,

public function foo()
{
    return $this->hasOne('App\City', 'id', 'city_id');
}

on my view

{{$listing->foo->name}}

This one works.

What cause the problem with city method name? I have never problem with city method name in other projects.

Upvotes: 0

Views: 148

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

It looks like you use city as object's attribute somewhere else in your code - it already contains the value so this value is used instead of the relation.

Look for some places where you set the value of $listing->city, try doing dd($listing->city) for a clue. And if you can't find it, post some more of your code, as the error lies somewhere else than what you posted so far.

Upvotes: 2

Related Questions