TypeError: Wrong Return Type

Fatal error: Uncaught TypeError: App\Service\UserService::findUser(): Return value must be of type App\Entity\User, null returned

Quick Answer

A function returned a value that does not match its declared return type. Either change the return type to be nullable or ensure the function always returns the correct type.

Why This Happens

When a function declares a return type like : User, PHP enforces that the returned value matches. Returning null from a non-nullable return type or returning the wrong type triggers this error. This is common with find/lookup methods that may not find a result.

The Problem

function findUser(int $id): User {
    $user = $this->repository->find($id);
    return $user; // Returns null when not found
}

The Fix

function findUser(int $id): ?User {
    return $this->repository->find($id);
}

// Or throw an exception:
function findUserOrFail(int $id): User {
    $user = $this->repository->find($id);
    if ($user === null) {
        throw new NotFoundException("User $id not found");
    }
    return $user;
}

Step-by-Step Fix

  1. 1

    Check the return type declaration

    Look at the function signature to see what return type is declared and compare it with what is actually being returned.

  2. 2

    Determine if null is valid

    Decide whether the function should legitimately return null. If so, add ? to make the return type nullable.

  3. 3

    Handle the missing value

    If null is not valid, add a check before returning and throw a descriptive exception when the expected value is not found.

Got the actual stack trace?

Paste it into our free AI explainer to get the cause and the fix for your specific case — no signup, nothing to install.

Explain my error

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free