Guest User

Untitled

a guest
Apr 22nd, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.46 KB | None | 0 0
  1. <?php
  2.  
  3. // User 1 exists, with account
  4. $user1 = User::find(1);
  5. $accountId = $user1->account->id; // 123
  6.  
  7. // User 2 exists, without account
  8. $user2 = User::find(2);
  9. $accountId = $user2->account->id; // PHP Error: Trying to get property of non-object
  10.  
  11. // Fix without optional()
  12. $accountId = $user2->account ? $user2->account->id : null; // null
  13. $accountId = $user2->account->id ?? null; // null
  14.  
  15. // Fix with optional()
  16. $accountId = optional($user2->account)->id; // null
Add Comment
Please, Sign In to add comment