terinao
terinao

Reputation: 489

Laravel belongsTo relationship returns empty object

post.php

class post extends Model
{
   use HasFactory;
   public function publisher()
   {
       return $this->belongsTo('App\Models\User');
   }
   protected $fillable = ['title','image','price','Describtion','image1','image2','image3','image4','publisher'];
    
}

Fetchpost.php

class Fetchpost extends Component
{
   use WithPagination;

   public function render()
   {
       return view('livewire.fetchpost', ['posts' => post::orderBy('created_at', 'desc')->paginate(10)],);
   }
}

fetchpost.blade.php

<div>
    @foreach($posts as post)
        <img class="rounded" src="{{ $post->publisher->profile_photo_path }}">
        <h1>{{ $post->publisher }}</h1>
        <h3>{{ $post->title }}</h1>
        <p>{{ $post->Description }}</p>
    @endforeach
</div>

so what i'm trying to achieve is to show post with publisher profile info like name and profile photo (like facebook), but i am getting error

Trying to get property 'profile_photo_path' of non-object

Upvotes: 0

Views: 346

Answers (1)

zahid hasan emon
zahid hasan emon

Reputation: 6233

the problem here is, you are not passing a foreign key explicitly in relationship. so using naming convention for relationship definition, laravel is looking for a publisher_id (relationship method name _ primary key of the parent table) column in your post table. but there's none as your foreign key is publisher only and laravel can't a build a relationship. thus you are getting your error trying to get property of non object. it's a good practice to reference the foreign key in relationship. or make the foreign key using laravel convention.

public function publisher()
{
    return $this->belongsTo('App\Models\User', 'publisher');
}

Upvotes: 1

Related Questions