Skip to content
Advertisement

laravel – How can I get the user information of each comment

I have these Models:

class Post extends Model
{
    protected $primaryKey = 'post_id';
    public function comments()
    {
        return $this->hasMany(Comment::class, 'post_id', 'post_id');
    }
}

class Comment extends Model
{
    protected $primaryKey = 'comment_id';

    public function post()
    {
        return $this->belongsTo(Post::class, 'post_id');
    }
}

class User extends Authenticatable
{
    protected $primaryKey = 'user_id';
    public function comments()
    {
        return $this->hasMany(Comment::class, 'user_id', 'commenter_id');
    }
}

class MyController extends Controller
{
    public function post($id = null)
    {
        $post = Post::where('post_id', $id)->first();
        $comments = $post->comments;
    }
}

What I want is to get the user of each comment something like $post->comments->user in order to get the user information easy like below:

@foreach($post->comments as $comment)
    {{ $comment->user->first_name.' '.$comment->user->last_name }}
@endforeach

How can I do this? I guess I need something named hasManyThrough but it’s too complex and I got confused 😐

Advertisement

Answer

Yes you can get the user object with comment object, using

$post = Post::with('comments.user')->where('post_id', $id)->first();

and define mapping for user in comments models

class Comment extends Model
{
    protected $primaryKey = 'comment_id';

    public function post()
    {
        return $this->belongsTo(Post::class, 'post_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement