I'm trying to get the usernames of the users who have posted comments, however, I keep getting "Trying to get property 'username' of non-object" error. I believe my relationships are done correctly but I might be wrong.
My tables:
Table: Users
Columns: id, username, password
Table: Comments
Columns: id, user_id, image_id, comment
Comment model:
class Comment extends Model
{
public function users(){
return $this->belongsTo('App\User');
}
}
User model:
class User extends Model implements Authenticatable
{
public function comments(){
return $this->hasMany('App\Comment');
}
}
I'm getting the comments like this:
$comments = Comment::with('users')->where('image_id', $id)->get();
And then trying to loop through them in the view like this:
@foreach($comments as $comment)
<p>{{ $comment->comment }}</p>
<p>{{ $comment->users->username }}</p>
@endforeach
And when I dd($comments), I see:
#relations: array:1 [▼
"users" => null
]
I'm not sure why is it null though.