Laravel Relation “Attempt to read property on null”

Laravel property on null

It usually means that the related record is NULL or soft-deleted. There are multiple ways to gracefully handle such a situation, without showing the error to the user.

A practical example would be a list of Posts with belongs To relation to Categories.

Migration file for Posts:






Now, have you noticed that migration says the category_id field is nullable()?

So yeah, the code of $post->category->name would throw the error in that case:

Attempt to read property “name” on null

What are our options to handle this nullable field?

Option 1. ‘??’ Operator in Blade

Just replace this:

With this:


It’s a PHP so-called “Null Coalescing Operator

Instead of the empty string, you may provide any value you want:

Option 2. optional() in Blade

A similar fix comes not from PHP but from the Laravel layer, in the form of optional() helper.

Just replace this:

With this:

It will show the empty string for the name, without throwing any errors.

It acts almost the same as the Null Coalesce Operator above, with the slight difference of intention how you use it.

Option 3. PHP 8: Nullsafe Operator

A newer addition to PHP language is an operator that allows us to call the chained objects or even methods, without being afraid of them returning null.

As Brent points out in his article on the Nullsafe Operator, PHP 8 allows you to write this:

So, in our case, we can have a one-character solution!

Just replace this:

With this:

It will also return an empty string, without errors.

Option 4. withDefault() in Model

All the options above work on the Blade level, or wherever you present that relationship. But what if you call it multiple times in different parts of the codebase, and you want to define that relation behavior once, instead, by providing some default values?

You can add a default “fallback” model inside of the related method.



Then, in case of the related model not existing, Eloquent will artificially create an empty model of Category. It would then not trigger the PHP error of “property on null“, because the object is not null. It has empty data inside, but not null anymore.

Not only that, you can specify the default values as an array inside of that withDefault() model:

This option is more suitable as a global solution when you don’t want to describe the defaults everywhere you would use it in Blade files or other places in code. Define it once in the Model and kinda forget about it.

Want me to do this for you? Drop me a line: itgalaxyzzz {at} gmail [dot] com