Syed Saqlain
Syed Saqlain

Reputation: 574

Error Laravel 5.8 Eloquent - Trying to get property 'name' of non-object

I am working in Laravel 5.8 and struggling with a strange error.. I want to display Blog author name on blog detail page but it gives me error Trying to get property 'name' of non-object

My Relation :

Blogs > Author

class Blog extends Model
{

    public function author_name(){
        return $this->belongsTo(Admin::class);
    }

}

Admin Model

class Admin extends Authenticatable
{

    public function blogs() {
        return $this->hasMany('App\Blog');
    }

}

detail.blade.php

{{ $blog->author_name->name }}

P.S : if I dd($blog->author_name) it gives correct id of author but when i call ->name object. it gives above error

Upvotes: 1

Views: 645

Answers (1)

Jithesh Jose
Jithesh Jose

Reputation: 1814

Add keys to relationships.

class Blog extends Model
{
public function author_name()
{
    return $this->belongsTo('App\Admin','blog_id','blog_id'); //add your local key and foreign key here
}
}

class Admin extends Authenticatable
{
public function blogs() {
    return $this->hasMany('App\Blog','blog_id','blog_id'); //add your local key and foreign key here
}
}

You can retrieve data by using

$blog = Blog::where('blog_id',1);
if(isset($blog->author_name))
  echo $blog->author_name->name;

Upvotes: 4

Related Questions