Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // User 1 exists, with account
- $user1 = User::find(1);
- $accountId = $user1->account->id; // 123
- // User 2 exists, without account
- $user2 = User::find(2);
- $accountId = $user2->account->id; // PHP Error: Trying to get property of non-object
- // Fix without optional()
- $accountId = $user2->account ? $user2->account->id : null; // null
- $accountId = $user2->account->id ?? null; // null
- // Fix with optional()
- $accountId = optional($user2->account)->id; // null
Add Comment
Please, Sign In to add comment