Skip to content

Instantly share code, notes, and snippets.

@monish-khatri
Last active September 6, 2023 05:49
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 monish-khatri/1e526e419c1a1d8adc38a205a75cf536 to your computer and use it in GitHub Desktop.
Save monish-khatri/1e526e419c1a1d8adc38a205a75cf536 to your computer and use it in GitHub Desktop.
<?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