Last active
September 6, 2023 05:49
-
-
Save monish-khatri/1e526e419c1a1d8adc38a205a75cf536 to your computer and use it in GitHub Desktop.
This file contains 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 | |
// Facing `Warning: Attempt to read property "name" on null`? | |
$name = $user->name; | |
/** | |
* To overcome the above error there are 3 ways in laravel | |
* 1) if-else condition [Not recommended] | |
* 2) null safe operator [Available from php8.0] | |
* 3) optional helper [Best Way] | |
*/ | |
$name = $user?->name; // Less clean and readable | |
$name = optional($user)->name; // Clean & readable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment