Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

markbell's avatar

Relationships with column in same table

I have a category table. I also offer sub-categories on this app. I have a foreign key ('parent') on my categories table which refers to the 'id' column on the same table.

My relationship looks like so

public function parentcat()
    {
        return $this->belongsTo(Category::class, 'parent');
    }

When I run Tinker..

$category = \App\Category::find(2)
$category->parentcat->name

It returns the name of the parent category as expected.

In the view; I am outputting the results in a table. If I print

$category->parentcat

I get


// The model object. (Laracasts strips it out though!) Cheers @JeffreyWay  :p

But if I add

$category->parentcat->name

I get an exception 'Trying to get property of non-object'

What am I doing wrong?

TIA, Mark

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

Not all categories have parents? For the rows that have no parent, you will get an error if you try to access a property of parentCat

So you need to code for that in your blade which can be done with 'or' in the blade tag, or the null coalesce operator in PHP 7 ??

<td>{{$category->name}}</td><td>{{$category->parentcat->name ?? ''}}</td> 
2 likes

Please or to participate in this conversation.