简体   繁体   中英

Laravel HasMany returning true on empty() on PHP7 upgrade

We are migrating an older Laravel 4 app to PHP 7. Currently this blade code returns false on PHP 5.6:

@if(empty($review->region->region_slug) || empty($review->city->city_slug) || empty($review->park->park_slug))

However, once we try to run this on PHP 7, it returns true. I traced it back and found this returns true:

empty($review->region->region_slug)

HOWEVER, if I use that beforehand, it will then return false. Example:

echo $review->region->region_slug;

echo empty($review->region->region_slug) ? 'TRUE' : 'FALSE';

The slug will be returned AND FALSE will be returned.

The review model has the relationship like so:

    public function region()
    {
        return $this->belongsTo('Region', 'cgr_region_id');
    }

Which appears to be correct. I am at a loss here.

I resolved this by loading the object eagerly. So instead of:

Reviews::findOrFail($id); 

I load it like:

Reviews::with('region', 'city', 'park')->findOrFail($id);

This is actually a result of the Eloquent Collection which has likely come a long way since Laravel 4. Basically, the collection object is not empty , only the fillable collection properties are. So, to fix this, you can simply call the isEmpty() method on the collection object and if it is truly empty, your ternary operation should work properly.

This should work:

echo ($review->region->region_slug)->isEmpty() ? 'TRUE' : 'FALSE';

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM