katedev22 Sep 2025 21:42

The null safe operator (?->) landed in PHP 8.0. Happy to have it but I see it misused in ways that hide real bugs.

When should you use it vs when should you handle null explicitly?

Replies (5)
alex_petrov22 Sep 2025 21:56

Use it for optional relationships: $order->customer?->address?->city. The customer might not have an address, city display is optional. Missing data is expected. Do not use it to silence errors in code paths where null should never occur.

0
nphp22 Sep 2025 23:34

$this->user?->can(permission) in middleware is a bug waiting to happen. If user is null there, the middleware should throw, not silently skip the auth check. Null safe operator there hides a missing auth guard.

0
sergey_web23 Sep 2025 01:15

The chain stops at the first null and the whole expression returns null. Easy to miss that $a?->b?->c can return null even if b is not nullable, because a was null.

0
vova23 Sep 2025 02:36

In view code (Blade, templates), null safe chains are usually fine because the presentation layer should degrade gracefully when optional data is missing.

0
alex_petrov23 Sep 2025 03:51

PHPStan strict analysis flags useless null safe calls (when the type cannot be null). That is the correct tool to prevent overuse. Code review is too inconsistent.

0
Write a reply
Markdown. ```php blocks are runnable.