Reputation: 70
I'm trying to make a realtionship between my comments model and user model so I can fetch the user's avatar on my post view. I'm pretty new to the eloquent syntax so please bare with me.
Comments.php
protected $table = 'ucp_news_comments';
public function user() {
return $this->belongsTo(User::class);
}
User.php
protected $table = 'core_accounts';
public function comments() {
return $this->hasMany(Comments::class, 'poster_id', 'id');
}
post.blade.php
@foreach($comments as $comment)
<img src="{{ asset('/storage/images/.$comment->user->image) }}" alt="">
@endforeach
My error on the post.blade.php is Undefined property: stdClass::$user
Comments are loading perfectly, just stumped on how to retrieve avatar from user model through the comment. Thank you for taking your time out of your day to look at my code and provide help to me, greatly appreciated.
Upvotes: 0
Views: 29
Reputation: 2987
you don't name your primary key and foreign key field as Laravel expected so you need to tell Laravel what the primary key and foreign key are.
public function user() {
return $this->belongsTo(User::class, 'poster_id');
}
Upvotes: 1