Skip to content

Instantly share code, notes, and snippets.

@Mombuyish
Created April 14, 2018 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mombuyish/4d461e7ee90bf0370c3dff22369c2578 to your computer and use it in GitHub Desktop.
Save Mombuyish/4d461e7ee90bf0370c3dff22369c2578 to your computer and use it in GitHub Desktop.
<?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