No need to go through it all and then if you are diligent and want to check what getAttributes
or toArray
Laravel functions return and what happens, we can use a combination of isset
and is_null
PHP core functions. I am concentrating here on Laravel and corresponding relationsip which is a bit of a more complex example but all the other variants can be extracted from below code. Enjoy and I hope it will save time.
Let me try to elaborate with full proof Laravel example and Artisan Tinker.
Please bear with me.
Thank you PHP Artisan Tinker!
/**
* @return \Illuminate\Database\Eloquent\Model|HasMany|object|null
*/
public function profile(): HasMany
{
return $this->hasMany(User_profile::class, 'user_id', 'user_id')
->orderBy('created_at', 'desc');
}
php artisan tinker
>>> $u = (new App\Models\User())->find(11549)
=> App\Models\User {#3481
user_id: 11549,
created_at: "2019-10-31 09:26:14",
updated_at: "2019-10-31 09:26:14",
first_name: "Pippy",
middle_name: null,
last_name: "Longstocking",
phone: null,
email: "11544@example.com",
pincode: null,
flag_is_active: 0,
flag_is_email_subscribed: 1,
flag_is_mobile_subscribed: 1,
flag_terms_agreed: 1,
flag_is_blocked: 0,
flag_delete: 0,
where_from: 1,
employee_status: 0,
remember_token: null,
user_reference: "11544",
alternate_user_reference: "11544",
user_transaction_reference: null,
user_channel: null,
campaign_id: 0,
ip_address: "172.31.10.23",
}
>>> $u->profile()
=> Illuminate\Database\Eloquent\Relations\HasMany {#3483}
>>> $userProfile=$u->profile()->first();
=> null
>>> $userProfile->flag_ifisa
PHP Notice: Trying to get property 'flag_ifisa' of non-object in Psy Shell code on line 1
>>> $userProfile->toArray()
PHP Error: Call to a member function toArray() on null in Psy Shell code on line 1
>>> $userProfile->getAttributes()
PHP Error: Call to a member function getAttributes() on null in Psy Shell code on line 1
>>> is_null($userProfile)
=> true
>>> isset($userProfile->flag_ifisa)
=> false