Fix "Call to a member function … on null" in PHP and Laravel
Error: Call to a member function update() on null
- Call to a member function format() on null
- Error: Call to a member function getClientOriginalName() on null
- Call to a member function format() on bool
- Symfony\Component\ErrorHandler\Error\FatalError: Call to a member function save() on null
- Warning: Attempt to read property "name" on null
You are calling a method (->update()) on a variable that is null. In Laravel it is almost always a query that found nothing (first(), find() return null), an empty relation or auth()->user() for a guest. Use findOrFail() / firstOrFail() to return a clean 404, or handle the null case with an if or the ?-> operator.
What this error means
The -> operator only works on an object. If the expression on its left is null (or false, an array, a string), PHP throws an Error (a Throwable, not an Exception) with the message "Call to a member function x() on null". The method name shows where it happened, but the culprit is the expression right before it. With Eloquent, first(), find() and firstWhere() return null when no row matches, a belongsTo or hasOne relation returns null when the foreign key is empty, and $request->file() returns null when no file was sent. The same problem when reading gives "Attempt to read property "x" on null".
Common causes
- Eloquent query with no result:
User::where('email', $email)->first()->update(...)orPost::find($id)with an id that does not exist (anymore). - Empty relation:
$order->customer->namewhencustomer_idisnullor the customer was deleted, soft deletes included. - Guest user:
auth()->user()->idon a route without theauthmiddleware, or in a job, an Artisan command or a scheduled task where there is no session. - File not received:
$request->file('avatar')->store(...)with no file, a form withoutenctype="multipart/form-data", or a file larger thanupload_max_filesize. - Function returning
false:DateTime::createFromFormat()returnsfalsewhen the date does not match the format, hence "Call to a member function format() on bool".
Step-by-step fix
-
Find the expression that is
nullOpen the file and line from the stack trace (in Laravel, the error page highlights them). Dump the variable before
->to understand why it is empty.$user = User::where('email', $email)->first(); dd($email, $user); -
Return a 404 when the resource must exist
findOrFail()andfirstOrFail()throwModelNotFoundException, which Laravel turns into a 404 page. Route model binding does the same automatically.$post = Post::where('slug', $slug)->firstOrFail(); $post->update(['views' => $post->views + 1]); // routes/web.php: route model binding, 404 if not found Route::get('/posts/{post:slug}', [PostController::class, 'show']); // PostController public function show(Post $post) { return view('posts.show', compact('post')); } -
Handle the
nullcase when it is expectedIf absence is an expected case, test for it and respond properly. The nullsafe operator
?->(PHP 8.0+) is fine to read a value; avoid it for a write such as?->update(), which would silently do nothing.$user = User::firstWhere('email', $request->input('email')); if ($user === null) { return back()->withErrors(['email' => 'No account found for this email.']); } $name = $order->customer?->name ?? 'Deleted customer'; -
Relations: provide a default model
On a
belongsTo,hasOneorhasOneThroughrelation,withDefault()returns an empty model instead ofnull, which is handy for display.use Illuminate\Database\Eloquent\Relations\BelongsTo; public function customer(): BelongsTo { return $this->belongsTo(Customer::class)->withDefault([ 'name' => 'Deleted customer', ]); } -
User and files: protect the route and validate
Add the
authmiddleware to routes that useauth()->user(), and validate that the file is present before handling it.Route::post('/profile/avatar', [ProfileController::class, 'avatar'])->middleware('auth'); // ProfileController $request->validate(['avatar' => 'required|image|max:2048']); $path = $request->file('avatar')->store('avatars', 'public'); $request->user()->update(['avatar_path' => $path]); -
Plain PHP: check for
falsereturn valuesMany native functions return
falseon failure. Check the result before calling a method on it.$date = DateTime::createFromFormat('d/m/Y', $input); if ($date === false) { throw new InvalidArgumentException('Invalid date: ' . $input); } echo $date->format('Y-m-d');
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Use
findOrFail(),firstOrFail()or route model binding in controllers whenever the resource must exist. - Run Larastan (PHPStan for Laravel): it flags method calls on a
Model|nulltype before they reach production. - Declare foreign keys with
constrained()and an explicit delete rule (cascadeOnDelete()ornullOnDelete()) so you know when a relation can be empty.
Frequently asked questions
What is the difference between first() and firstOrFail()?
first() returns null when nothing matches, firstOrFail() throws a ModelNotFoundException that Laravel renders as a 404. Same logic for find() and findOrFail().
Why does it work locally but not in production?
The data differs: a record present in your local database (seeders, tests) does not exist in production, or a related row was deleted there. The code assumes the row always exists.
Should I replace every -> with ?->?
No. ?-> hides the missing value. Use it only when null is a normal case; otherwise fail clearly with findOrFail() or an exception.
Useful tools for this error
More PHP & Laravel errors
- Fix "419 Page Expired" in Laravel (CSRF token mismatch)
- Fix "Allowed memory size of 134217728 bytes exhausted" in PHP
- Fix "Target class [X] does not exist" and "Class not found" in Laravel
- Fix "SQLSTATE[HY000] [2002] Connection refused" in Laravel
- Fix "No application encryption key has been specified" in Laravel
- Fix "Your requirements could not be resolved to an installable set of packages" (Composer)
- Fix "laravel.log could not be opened in append mode: Permission denied"
- Fix "Vite manifest not found at: public/build/manifest.json" in Laravel