"Trying to get property 'x' of non-object" With Null Coalescing Operator in PHP

Quick one here but today, thanks to Tez on Stack Overflow, I discovered that PHP's null coalescing operator (the double question mark operator) can fail when you use a function at any part of the statement.

Here's the example in Laravel I had. I was trying to find the ID of a related object and guarantee that it will be set to null otherwise:

$id = $user->organisation->departments->first()->id ?? null;

I didn't see anything wrong with the code and expected it to give me the ID of the first department on the user's organisation or null if any relationship didn't exist.

However, I got the following error when the organisation relationship was empty:

ErrorException: Trying to get property 'departments' of non-object

I was wracking my brain trying to work out the problem as I assumed null coalescing would just handle any part of the statement evaluating to null or unset. But apparently, no matter where in the statement it is, having a function call will break that.

The Fix in Laravel

Step in Laravel Collection's Higher Order Messages, which give dynamic property access to common collection functions, including first(). So I could just remove the function call directly:

$id = $user->organisation->departments->first->id->id ?? null;

Side Note

A first version of this blog used the incorrect code to access the id parameter. id is referenced twice in the statement, the first essentially as a parameter to the first dynamic property, specifying that the first item should be found where the id property is set. The second accessing the property on the object itself.

This part is a little confusing but is explained in the Laravel github issue I opened.

Super easy (less with the edit)! I love discovering a new Laravel feature!

Posted on Aug 06, 2020

Tagged

Discuss This

blog comments powered by Disqus