you user can only have one role, so rename roles to role.
Eager load comment user and role like
$post->comments()->with('user.role')->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello guys,
I am currently trying to implement a comment section. As of now I associate the comments with the post and display them correctly together with the user.
Now I also want to get the roles of the user and I don't really know how to proceed. My usertable has a foreign key for a role
Schema::create('users', function (Blueprint $table) {
$table->foreignIdFor(Role::class)->default(1);
...
}
And my comments are also linked to the user and post by a foreign key
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->foreignIdFor(Post::class);
$table->foreignIdFor(User::class);
...
}
To link the comments to the user I have the following in my CommentModel:
public function user() : BelongsTo {
return $this->BelongsTo(User::class);
}
To link the user to a role I have the following in my UserModel:
public function roles() : belongsTo {
return $this->belongsTo(Role::class);
}
So in my understanding, since I've got the post linked to the comments, the comments linked to the user and the user linked to the roles, I should be able to get the roles of the individual comments by doing this in my PostController:
'roles' => $post->comments()->user()->with('roles')
But this returns "NULL". I can however freely query the users to the comments, so I don't think I made a mistake there. But is there something I missed or am I doing this completely wrong?
you user can only have one role, so rename roles to role.
Eager load comment user and role like
$post->comments()->with('user.role')->get();
Please or to participate in this conversation.