Null Reference Errors
Also Known As
TL;DR
Explanation
A null reference error occurs when code assumes a variable holds an object but it holds null instead. In PHP: $user->getName() when $user is null throws 'Call to a member function getName() on null'. Common causes: database queries that return null when no record is found (User::find($id) returns null if the user does not exist); optional relationships not loaded; functions that return null on failure without signalling this in the type signature. Solutions: null checks (if ($user !== null)); nullsafe operator (PHP 8.0+: $user?->getName()); strict return types and null coalescing ($user ?? throw new NotFoundException()); using findOrFail() in Eloquent which throws ModelNotFoundException instead of returning null. In JavaScript: optional chaining (user?.name) prevents the error. PHP 8.0's nullsafe operator (?->) chains method calls that short-circuit to null if any step is null.
Common Misconception
Why It Matters
Common Mistakes
- Using User::find($id) without checking for null — use findOrFail($id) to throw an exception, or check $user !== null before use.
- Accessing relationship properties without checking if the relationship is loaded — $post->author->name throws if author is null (no related record).
- Not declaring return types as nullable (?User) when a function can return null — the type signature should communicate nullability.
- Suppressing the error with @ instead of handling it — @$user->name silences the error but the variable is still null and the behaviour is undefined.
Code Examples
// No null check — throws on missing user
$user = User::find($id);
echo $user->getName(); // 'Call to member function on null'
// Nested null checks — verbose and easy to miss
if ($user !== null) {
if ($user->getProfile() !== null) {
echo $user->getProfile()->getAvatar();
}
}
// findOrFail throws ModelNotFoundException — handled centrally
$user = User::findOrFail($id);
echo $user->getName(); // safe — exception if not found
// PHP 8 nullsafe operator — chains short-circuit to null
echo $user?->getProfile()?->getAvatar() ?? 'default-avatar.png';
// Eloquent: fail fast at the data layer
try {
$order = Order::findOrFail($orderId);
} catch (ModelNotFoundException $e) {
return response()->json(['error' => 'Order not found'], 404);
}