How to solve “Attempt to read property of Null”

Sometimes in Laravel, when you try to show a property of an object, for example :

{{ $user->name }}

you get an error like this :

Attempt to read property on null

which simply means that the object itself “user” is null and you can’t get a name property of Null. To solve this, you need to make sure that the user object is there first and then get the name but that will be a lot of coding and if statement, while there is a one-character solution to this, it is called a Nullsafe Operator and it is in PHP 8
the code will look like this

{{ $user?->name }}

you can use the same method in a chain of objects or even methods

$country = $session?->user?->getAddress()?->country;

There are other options that you can check in this article

Leave a Reply

Your email address will not be published. Required fields are marked *