Call to member function on null 🐘 PHP

Fatal error: Uncaught Error: Call to a member function x() on null

Code called a method on a variable that is null instead of an object.

Seen on: PHP

Meaning

The object you expected was never created or a lookup failed. It is PHP’s equivalent of a null pointer exception and is very common with ORMs (find() returns null) and DOM parsing.

Common causes

  • Model lookup returned null (User::find($id))
  • Dependency not injected / service not initialised
  • Method chain where an earlier call returned null
  • Database connection object never created

⚡ Quick fix

  1. Check for null before calling: if ($user) { … }
  2. Use findOrFail() in Laravel to get a 404 instead
  3. Use the nullsafe operator $user?->profile?->name (PHP 8)

Detailed fix by platform

PHP

  1. Laravel — replace Model::find() with findOrFail() when the record must exist

Code examples

Nullsafe operator

php
$city = $order?->customer?->address?->city ?? 'Unknown';

How to diagnose

  1. Object — Which variable is null (the method name tells you)?
  2. Source — Where should it be created/fetched?

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.