Bill Garrison Bill Garrison - 2 years ago 263
PHP Question

Laravel 5.2 - PHP 7.0.6 coalesce operators returning empty strings

So I have a project that relies on Laravel 5.2 / PHP 7.0.6 and it uses Transformers to deal with API responses. In MANY places in our code we use the new php 7 coalescing (??) operators. However, since our update to php 7.0.6 we are seeing a lot of the following:


'vip_id' => $beneficiaryQdro->beneficiary->vip_id ?? ''

Expected Result: 11583 (the vip id of the beneficiary relationship)

Actual Result: ''

I have tried running this:
and I get the proper vip_id returned. However, when I add on the coalescing operator it once again returns an empty string. This WAS working before. Anyone else seen this happen with the new php release?

Update: I have fixed it by eager loading the relationship. Something about the coalesce operator doesn't like dealing with a relationship where it fills in the information on the fly. I'm not sure who's issue this becomes. Before 7.0.6 coalescing operators were dealing with relationships that weren't eager loaded just fine but this update broke it somehow.

Answer Source


$beneficiaryQdro->beneficiary->vip_id ?? ''

is the same as doing:

isset($beneficiaryQdro->beneficiary->vip_id) ? $beneficiaryQdro->beneficiary->vip_id : ''

So unless the beneficiary relationship is loaded this will always be false when doing isset and result in being ''.

There are 2 bugs fixed in PHP 7.0.6 that look like they relate to the issue you're having:

Coalescing operator on classes with overridden __get() method

Null coalescing operator and ArrayAccess

So it could be an issue with how Eloquent is handling it with its magic methods. I don't have an install under PHP 7 to confirm this though.

Looks like this was also asked here:

It looks like it shouldn't have worked pre 7.0.6.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download