Last Updated: July 25, 2019
·
3.207K
· twoseats

Laravel 4 Eloquent ORM Relationships

AKA The Property Of Non Object Headache

So; I spent a good set of hours mulling over the apparent error in my code that was generating a "Trying to access property of non object" error.
I had actually already made every step I found whilst googling & found myself at a dead end.

The Premise

I was eager loading this relationship (which is a good practise to save on processing time), but couldn't access the property when trying to display it.

My situation was a little different to most of the ones I came across; in my eloquent model I had similar relationships that I referred to as such:

// this worked fine when called
// it refers to an objects "origin" which is a country
public function origin()
{
    return $this->belongsTo('Country', 'origin_id');
}

// this didn't work
// it refers to an optional alternative "origin"
public function alt_origin()
{
    return $this->belongsTo('Country', 'alt_origin_id');
}

As you can no doubt see the functions do exactly the same thing (different ids being referenced aside), but one worked whilst the other did not... Perplexing indeed.

What was wrong? AKA How to fix it.

Basically L4 doesn't seem to like relationship function names defined using Snake Case. A fix to the following using Camel Case solved all my woes on that pesky second function.

public function altOrigin()
{
    return $this->belongsTo('Country', 'alt_origin_id');
}

Hopefully I just saved someone some time :)

3 Responses
Add your response

thank you!!

over 1 year ago ·

you're most welcome!

over 1 year ago ·

Found out that you have to define the relationship with camelCase but you can fetch the property with snake_case.

public function altOrigin() { ... }

Then:

$instance->alt_origin->name

over 1 year ago ·