Solving Laravel ErrorException: Trying to get property of non-object (4 solutions)

Updated: January 16, 2024 By: Guest Contributor Post a comment

The Problem

The ErrorException: Trying to get property of non-object is a common issue that Laravel developers encounter. This error occurs when you attempt to access a property or method on a variable that is not an object. In Laravel, this is often the result of a misconception about what a particular function or method is returning or when you try to access a relationship or attribute on a model that does not exist. Let’s explore several ways to resolve this issue.

Let’s Fix It

Solution 1 – Check Object Existence Before Access

Before attempting to access properties on an object, it’s crucial to ensure that the variable in question actually holds an object.

  1. Begin by identifying the piece of code where the error is thrown.
  2. Confirm whether the expected object should exist at this point in your code.
  3. Utilize an if statement or a ternary operator to check for the object existence beforehand.
  4. Access the object properties only if the object exists.

Example:

if (is_object($user)) {
    echo $user->name;
} else {
    echo 'User object does not exist.';
}

Notes: This approach is simple and ensures you are not accessing properties on a non-existent object. However, it doesn’t solve the underlying issue of why the object is not instantiated correctly but helps avoid runtime exceptions.

Solution 2 – Use Optional Helper

Laravel provides a helper function optional() to help avoid trying to access properties or methods on a non-object.

  1. Wrap the object variable with the optional() function.
  2. Attempt to access the property or method as you normally would.

Example:

$name = optional($user)->name;

Notes: Using optional() is cleaner and more readable. It helps prevent errors but again does not solve the root cause. It also provides a straightforward way to specify a default value by chaining the ->value() method.

Solution 3 – Validate Database Records

Ensuring that you are retrieving a valid object from the database is another important check.

  1. Use Laravel’s query builder or Eloquent methods to retrieve data from the database.
  2. Check if the retrieved record is null before accessing its properties.
  3. Alternatively, use Eloquent’s find() or findOrFail() methods to automatically handle non-existent records.

Example:

$user = User::find($id);

if ($user) {
    echo $user->name;
} else {
    echo 'No user found with id ' . $id;
}

Notes: This solution helps to ascertain that the record exists in the database before any operations on it. findOrFail() will throw a ModelNotFoundException if no record is found, which can be caught and handled gracefully. However, if using find(), you still need to manually check for null.

Solution 4 – Leverage Eloquent Relationships Correctly

Incorrect usage of Eloquent relationships can also lead to this error. Here are steps to ensure relationships are loaded properly:

  1. Define correct Eloquent relationships in your models.
  2. Make use of eager loading with the with() method to prevent null relationships.
  3. Check for the existence of the relationship before accessing its properties.

Example:

$post = Post::with('author')->find($postId);

if ($post && $post->author) {
    echo $post->author->name;
} else {
    echo 'Post or author does not exist.';
}

Notes: This ensures that you’re working with correct and loaded relationships, which enriches the object approach in your application. It does require a solid understanding of how Eloquent relationships work, and the error may still occur if a relationship is expected but not present.

Final Words

Dealing with the ErrorException: Trying to get property of non-object is often about ensuring the robustness of your code against null references in objects. Start by diagnosing the context in which the error occurs and then proceed with an appropriate solution to check, handle, or prevent null objects appropriately. The underlying principle is to write defensive code that is expectant of possible null values and works around them intelligently.