@ryangurnick the answer is - yes
Eloquent Nullsafe Operator
Does anyone happen to know if eloquent supports the null safe operator?
The reason I ask if mainly due to an excessive amount of error checking needed to traverse more than one relationship when calling a model, it would be amazing if I could just use ?-> and check for a single null value.
My hope is that if this is not supported now that it will be shortly, but seeing as how laravel generally supports new php standards before I even know they exist, I am hoping the simple answer of YES comes from this thread.
I have not been able to find anything about this in the laravel documentation, hence the question.
Well… yes and no.
In general, yes, as @thinkverse says, the null-safe operator is a core PHP feature, so Eloquent ‘supports’ it just as much as it ‘supports’ == or >> or %.
But there are some extra considerations with Laravel collections (including Eloquent collections), which have a lot of method magic built into them. The same limitations that apply to the null-coalescing operator ?? also apply to the null-safe operator.
Specifically, attempting to access a nonexistent property on a collection will throw an exception rather than returning NULL (as it would with a model or any other regular PHP object), so null-coalescence or null-safety is no help. Assuming you have fetched a user and have a working posts relationship on your user model, the first two examples in the following will work as expected, whereas the last two will throw an exception:
$user_thingy = $user->thingy ?? 'a'; // → 'a'
$user_thingy = $user?->thingy; // → NULL
$post_thingy = $user->posts->thingy ?? 'a'; // throws exception
$post_thingy = $user->posts?->thingy; // throws exception
Note that $thingy in the last two examples is treated as a property of the collection itself, not a property of each post in the collection. The collection has no property called $thingy, so it looks instead for a higher-level function with that name; when it doesn’t find one, it throws an exception, before the null-coalescing or null-safe operator is even reached.
Please or to participate in this conversation.