How to fix “trying to get property of non-object” with PHP8 in Laravel

Categorized as Laravel, PHP Tagged

If you’re tired of the error “trying to get property of non-object”, you could use an optional helper method in Laravel. Also, if you’re using PHP8+ you could find the better way of dealing with these issues with the nullsafe operator. Here we go:

/*
* Checking if the property you're trying to get data from
* is NULL or not to prevent the classic error
* "trying to get property of non-object"
* We could use the "optional" helper method
* and with PHP8 and above we can use the nullsafe operator
*/

// You could do it this way:
$assignedUser = $task->assignedTo ? $task->assignedTo->name : NULL;

// Or, you could do it that way:
$assignedUser = optional($task->assignedTo)->name;

// ✅ Now you could do it in PHP8+ using the nullsafe operator
$assignedUser = $task->assignedTo?->name;

You can read the official PHP reference on this operator here – https://wiki.php.net/rfc/nullsafe_operator.

Leave a reply

Your email address will not be published.