xTheWolf
xTheWolf

Reputation: 1886

Laravel Eloquent Relationship Undefinded Property

I have a Model House and a Model energy_class.

A house has only one energy class. Energy Classes can be assigned to multiple houses. I therefore defined the relationships like this:

House.php

class House extends Model
{
    public function energy_class()
    {
        return $this->hasOne('App\energy_class', 'id', 'energy_class');
    }
}

energy_class.php

class energy_class extends Model
{
    public function house()
    {
        return $this->belongsToMany('App\House');
    }
}

When passing the House Data to a view like this:

$house = House::with('energy_class')->find($id);
return view('admin.houses.edit')->with('house', $house);

And referencing it on the view like this:

$house->energy_class()->name

I get this error: Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$name

When doing it like this: $house->energy_class->name I get trying to get property of non-object

Upvotes: 0

Views: 230

Answers (1)

visscher
visscher

Reputation: 304

Your first suggestion:

$house->energy_class()->name

Does not work, because at this point you only called the relationship, you didn't yet specify from it what you wanted, e.g.:

$house->energy_class()->first()

Your second try returns empty because $house->energy_class (which does the same as the above code), didn't return any results.

There can be various causes for this:

  • Your relationship is not properly signed up
  • Your database is not properly setup (have you set up a foreign key in your migration?)
  • The house actually does not have an energy class filled out

I suspect in your case it might be the second or the third. Could you paste me your migration script?

Edit: PS. if this error occurs because perhaps not each house actually has a an energy class, you could use the following code to check for this:

$house->energy_class ? $house->energy_class->name : "No energy class available";

Upvotes: 2

Related Questions