Created
April 14, 2018 09:59
-
-
Save Mombuyish/4d461e7ee90bf0370c3dff22369c2578 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment