Stop Using isset() – Use Laravel’s optional() Helper Instead
Stop Using isset() – Use Laravel’s optional() Helper Instead
In PHP, we often write multiple checks just to avoid the “Trying to get property of non-object” error. Laravel solves this with the optional() helper.
The Old Way
$user = User::find(1);
$name = isset($user) ? $user->profile->name ?? 'Guest' : 'Guest';
Messy, right? Lots of null checks.
The Laravel Way
$user = User::find(1);
$name = optional($user->profile)->name ?? 'Guest';
- No need for nested
isset()orif. optional()safely returnsnullif the object doesn’t exist.- Your code looks clean and readable.
Final Thought
The optional() helper is one of those tiny Laravel gems that makes your life easier. Whenever you’re checking for possible null objects, just wrap them with optional() — your code will be shorter, safer, and easier to understand.