0

i have a user and a profile model that every user hasOne profile . on some pages i wanted to check the profile of user field like below :

$user->profile->membership_id

now my application crashes when the ->profile does not exists i can use null coalesce the membership_id but i want to know if its possible to null safe the ->profile so if profile does not exists the application wont give error like below :

trying to get membership_id of none object
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
Farshad
  • 1,830
  • 6
  • 38
  • 70
  • Check if `$user->profile` exists before calling `->membership_id` – GrumpyCrouton Jan 15 '21 at 20:48
  • 2
    `null safe` is available as of PHP 8: `$user->profile?->membership_id`: https://wiki.php.net/rfc/nullsafe_operator – Tim Lewis Jan 15 '21 at 20:52
  • any way to use it in php 7 ? – Farshad Jan 15 '21 at 20:53
  • Why don't you use property_exists()? Edit: NVM Marcin Nabiałek got it. –  Jan 15 '21 at 20:53
  • @Farshad No, it's a new operator added in PHP 8, so you can't use it in PHP 7. There are other approaches (like `null coalesce` as you stated, and the answer below), but `null safe` will require you to update your PHP version. – Tim Lewis Jan 15 '21 at 21:03

1 Answers1

2

You can set default object adding withDefault to your relationship for example:

public function profile()
{
    return $this->belongsTo(Profile::class)->withDefault();
}

or

public function profile()
{
    return $this->belongsTo(Profile::class)->withDefault(['name' => 'No profile']);
}
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291