Solution for “Trying to get property of non-object” in Laravel

If you working with or loops in laravel (for, foreach, etc.) display access the data to getting the try to get property of non-object laravel or any types of the relationships like as a (one to many, many to many, etc.), this may mean that one of the Database queries is returning a null data variable or a null laravel 5/6/7 relationship member.

Is your query returning array or object?

first of all you can check your results means output using dd() or dump() in laravel. and then

  • you might find that it’s an array => an array access ([])
  • find that it’s an object then => an access (->).

Problem : Trying to get property of non-object

we are trying to echo out the name of the member in my document and we are getting the ErrorException: Trying to get property of non-object. My source codes below: Exception Trying to get property of non-object (View: in blade file)

Models

Reports

class Reports extends Model
    {
      public function postedBy()
      {
         return $this->belongsTo('App\Member');
      }
      protected $table = 'reports';
      protected $fillable = ['reportsContent', 'reportsTitle', 'postedBy'];
    }

Member

class Member extends Model implements AuthenticatableContract,
                                AuthorizableContract,
                                CanResetPasswordContract
    {
        use Authenticatable, Authorizable, CanResetPassword;

        protected $table = 'members';

        protected $fillable = ['name', 'email', 'password'];

        protected $hidden = ['password', 'remember_token'];

    }

Controller

public function showArticle($slug)
    {
        $document = Reports::where('slug', $slug)->firstOrFail();
        return view('document', compact('document'));
    }

Blade

{{ $document->postedBy->name }}

When We try to remove name in the blade file like {{ $document->postedBy }} it outputs the id, but when We try to add the ->name there it says Trying to get property of non-object but We have a field name in my table and a Member model. Are We missing something?

Solution

Is your query returning array or object? If you dump or dd it out, you might find that this is an array as well as all you need is an array access ([]) instead of an object access (->).

Second Opinion

$document->poster->name 

//to

$document->poster['name']

Next is to included a second parameter in my belongsTo, from

return $this->belongsTo('App\Member');
to

return $this->belongsTo('App\Member', 'member_id');

in which member_id is my foreign key in the reports Database table.

trying to get property of non-object laravel foreach

Solution 1


//Write 
{{ $memberDetail['id'] }} 
//instead of 
{{ $memberDetail->id }}

Solution 2

//Write
return view('backend.route_f_members.index', ['memberDetails'=>$memberDetails]);
//instead of
return view('backend.route_f_members.index', compact('memberDetails'));

trying to get property of non object

If you have a non-object variable, you can’t just use the “get” method to get its value. You need to use the “property” method. Here’s an example:

var obj = {}; obj.name = "Pakainfo"; console.log(obj.name); // "Pakainfo"

To get the value of obj.name property, you would use the following code:

console.log(obj.name.property); // "name"

The “Trying to get property of non-object” error in Laravel occurs when you try to access a property or method of an object that doesn’t exist or hasn’t been properly instantiated. This error is typically caused by one of the following:

  • Null values: If you try to access a property or method of a null value, you will get this error. For example, if you try to access a property of a model that doesn’t exist in the database, you might get this error.
  • Incorrect method chaining: If you chain methods together but one of them returns null instead of an object, you will get this error. For example, if you have a relationship that doesn’t exist, you might get this error when trying to access a related property.
  • Incorrect variable type: If you accidentally assign a non-object value to a variable that should hold an object, you will get this error when trying to access a property or method of the variable.
  • To fix this error, you need to identify which object or property is causing the problem and ensure that it exists and is properly instantiated. Here are some steps you can take:
  • Check the object instantiation: Make sure that the object you are trying to access is properly instantiated. If you are using a model, make sure it exists in the database before trying to access its properties.
  • Check for null values: Before accessing an object property, check that the object is not null. You can do this using the null coalescing operator (??) or the null conditional operator (->?).

For example:

$user = User::find(1);

// Using the null coalescing operator:
$name = $user->name ?? 'Unknown';

// Using the null conditional operator:
$email = $user->email->address->value->text->content->->?;   

Check the method chaining: Make sure that the methods you are chaining together return objects, not null values. If you are unsure which method is returning null, try splitting the chain into separate lines and checking the return value of each method.

$user = User::find(1);

// Incorrect method chaining:
$companyName = $user->company->name; // Error

// Correct method chaining:
$company = $user->company;
if ($company) {
    $companyName = $company->name;
} else {
    $companyName = 'Unknown';
}

Check the variable type: Make sure that the variable you are using to hold an object is actually an object. If you accidentally assign a non-object value to the variable, you will get this error when trying to access its properties.

For example:

$user = User::find(1);

// Incorrect variable assignment:
$company = $user->company_id; // Should be $user->company()

// Correct variable assignment:
$company = $user->company();
if ($company) {
    $companyName = $company->name;
} else {
    $companyName = 'Unknown';
}

By following these steps, you should be able to fix the “Trying to get property of non-object” error in Laravel.

I hope you get an idea about try to get property of non-object laravel.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment