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

Khudadad's avatar

Join using Eloguent

I have three tables (users,posts and comments) and want to retrieve a certain post with creator and all related comments on it. Such Laracast User model

public function posts()
{
    // A user can have many posts
    return $this->hasMany('App\Post');
}

public function comments()
{

// A user can have many comments return $this->hasMany('App\Comment'); }

Post model:

public function user()
{
    // A post is owned by a user
    return $this->belongsTo('App\User');
}

public function comments()
{
    // A post can have many comments
    return $this->hasMany('App\Comment');
}

Comment model:

 public function user()
{
    // A comment is owned by a user
    return $this->belongsTo('App\User');
}

    public function posts()
 {
         // A comment is owned by a post
        return $this->belongsTo('App\Post');
 }

Thanks

0 likes
5 replies
joedixon's avatar
Level 5

You can use something like the following:

$post = App\Post::find(1)
    ->with(['user', 'comments']);
    ->first()

You can then use the following to get the relevant details

$post->title //or whatever you need to get from the model

$post->user->name //get the owners name

//loop over the comments
foreach($post->comments as $comment){
    $comment->message //message comment
}

Hope this helps.

1 like
Devmaurice's avatar

Try using singular to denote one that way you will get it better. e.g in your comment

public function post()  //post not posts
 {
         // A comment is owned by a post
        return $this->belongsTo('App\Post');
 }

Now when easy as you say it:

comment->post

Khudadad's avatar

Thanks, Joedixon, but how do I get name of commenter

Khudadad's avatar

Thank you Devmaurice and Joedixon, Eloquent is awesome

1 like

Please or to participate in this conversation.