Knowledge
PHP: Call to a member function on null
#PHP
This error means you called a method on a variable that turned out to be null. The variable you expected to hold an object was empty, often a database lookup that found nothing.
Published by Mark van Eijk on June 23, 2026 · 1 minute read
About the error
Error: Call to a member function format() on null
You called a method (->format(), ->name, ->save()) on something that was null instead of the object you expected. PHP can't call a method on nothing, so it throws. In a web request this reaches visitors as a 500 Internal Server Error.
The method name in the message is a strong clue: it tells you which object was missing.
Why do I see this error
- A database query returned no row, so the model is
null. - A relationship isn't loaded or doesn't exist for this record.
- An optional value (a nullable column, a missing config key) is genuinely empty.
- A function you assumed always returns an object returned
nullon failure.
Solution
Find the null
In Laravel, find() and first() return null when nothing matches. Calling a method on that result fails:
$user = User::find($id); // null if no such user
echo $user->name; // Call to a member function on null
Handle the empty case
Decide what should happen when it's missing. To 404 automatically, use findOrFail():
$user = User::findOrFail($id); // throws a 404 instead of returning null
To provide a fallback, check first or use the nullsafe operator (PHP 8+):
// guard explicitly
if ($user) {
echo $user->name;
}
// or the nullsafe operator: returns null instead of erroring
echo $user?->profile?->bio ?? 'No bio';
Relationships
A relationship that hasn't been set returns null too. The nullsafe operator and optional() helper both guard against it:
$company = $user->company?->name ?? 'Independent';
The fix is rarely to suppress the error, it's to decide deliberately what the empty case should do. A related strictness error is the undefined array key warning in PHP 8.
Subscribe to our newsletter
Do you want to receive regular updates with fresh and exclusive content to learn more about web development, hosting, security and performance? Subscribe now!
Related articles
How to run PHP files
This error means you called a method on a variable that turned out to be null. The variable you expected to hold an object was empty, often a database lookup that found nothing.
PHP Fatal error: Class "X" not found
This error means you called a method on a variable that turned out to be null. The variable you expected to hold an object was empty, often a database lookup that found nothing.