Skip to content
Advertisement

Laravel Eloquent hasMany relationship

Hi I am new to Laravel and currently in am using Laravel 4.2. I am trying to create an application where I have users, posts and comments table and have the following model

User Model

function posts() {

    return $this->hasMany('Post');
}


function comments(){

    return $this->hasMany('Comment');
}

Post Model

function users() {

    return $this->belongsTo('User');
}

function comments() {

    return $this->hasMany('Comment');
}

Comment Model

function posts(){

    return $this->belongsTo('Post');
}

function users(){

    return $this->belongsTo('User');
}

What I want to achieve :

user’s Post and comment for Post

eg:: User1 -> Post one -> comment for post one

What I have done So far:::

$user = User::find(1);
$post = $user->posts()->get();

I am able to get post but how do i get comment for specific post??

Update

Thanks to @Bogdan for his help I am able to get post and comment for user. But as usual had another problem.

What I got:

 foreach($user->post AS $post) {

 foreach ($post->comment AS $comment ) {

 $comment->commentcontent; $user->uername;
}
}//first foreach

This is what I get

comment one by user1.
comment two by user1.

But in reality comment one is created by user1 and comment two is created by user2.

Thank you for your help in advance. Can post full code if needed.

Advertisement

Answer

You want to get user that made the comment, so get that user from the comment object.

Try this

$user = User::find(1);
$posts = $user->posts;

foreach ($posts as $post) {
    foreach ($post->comments as $comment) {
        echo $comment->commentcontent;
        echo $comment->users;
    }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement