how to fix Trying to get property ‘id’ of non-object in Laravel?

Today, We want to share with you trying to get property of non-object laravel.In this post we will show you trying to get property of non-object laravel foreach, hear for trying to get property of non-object laravel relationship we will give you demo and example for implement.In this post, we will learn about Solution for “Trying to get property of non-object” in Laravel with an example.

Solved – Trying to get property of non-object – Laravel

Problem
I’m trying to echo out the name of the merchant in my product and I’m getting the ErrorException: Trying to get property of non-object. My Laravel Full Source codes:

Also Read This 👉   Ajax Jquery Column Sorting Results using PHP MySQL

Models

1. Shops

class Shops extends Model
{
  public function uploadedInfo()
  {
     return $this->belongsTo('App\Merchant');
  }
  protected $table = 'shops';
  protected $fillable = ['shopsContent', 'shopsTitle', 'uploadedInfo'];
}

2. Merchant

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

    protected $table = 'merchants';

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

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

}

Controller

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

Blade File

{{ $product->uploadedInfo->name }}

When I try to remove name in the blade {{ $product->uploadedInfo }} it outputs the id, but when I try to add the ->name there it says Trying to get property of non-object but I have a field name in my table and a Merchant model. Am I missing something?

Free Live Chat for Any Issue

Best Solution for trying to get property of non-object laravel

Is your query returning array or object? If you dump it out, you might find that it’s an array and all you required is an array access ([]) instead of an object access (->).

Second Opinion

$product->poster->name

Into

Also Read This 👉   Facebook Graph API Search Multiple Parameters Queries

$product->poster['name']

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

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

Into
return $this->belongsTo('App\Merchant', 'merchant_id');

in which merchant_id is my foreign key in the shops table.

I hope you get an idea about Trying to get property ‘role’ of non-object.
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.

Rate this post