Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ventior's avatar

Get Roles of User of specific Comment

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?

0 likes
3 replies
Snapey's avatar
Snapey
Best Answer
Level 122

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();
1 like
Ventior's avatar

@Snapey Thanks a lot! It works now. Is there a good starting tutorial you'd recommend? I'm just kind of jumping from tutorial to tutorial when it comes to all the relations.

Snapey's avatar

@Ventior apparently Jeffrey Way's 30 days to learn laravel is good, but it very much depends where you are starting from

Please or to participate in this conversation.