2

I am using Laravel with Eloquent with MySQL.
I have three tables POSTS, USERS and COMMENTS. My POST and COMMENT are in one-to-many relation thus with the following code I get the list of Comments for particular POST id

$post =  Post::where('id', $id)->get();
$comment = Post::find($id)->comment()->paginate(10);       
return view('posts\single', ['post' => $post, 'comments' => $comment]);

Now I want to get the Details of each user from the USER table. I don't want to use the foreach() and then get details of every single ID. Is there any method by which I can get all the Comments (from COMMENTS table) including user details (from USER table) at a single call.

2
  • Using JOIN? w3schools.com/sql/sql_join.asp Commented Aug 29, 2017 at 12:16
  • You have to use eloquent relationships.. Commented Aug 29, 2017 at 12:36

3 Answers 3

1

you first need to create one to many relationship in USERS to COMMENTS (user have many comments).

and then you already have relation post have many comments relationship.

so, let's use Nested Eager Loading

$post =  Post::where('id', $id)->with('comments.user')->get();
return view('posts\single', ['post' => $post]);

now in your blade files....

  • $post->comments will give you all comments for particular post.
  • $post->comments->user will give you user who made a comment.
Sign up to request clarification or add additional context in comments.

2 Comments

Well Explained! Thanks a lot Maulik. Worked Like charm
welcome :) you should mark it as answered by clicking tick button under down arrow.
0

This should work. Try the following:

$comment = Comment::where('post_id', $post->id)->with('user')->paginate(10); 

1 Comment

That, unfortunately, is returning NULL at key user as "user"=>NULL
0

Please try with this -

User::join('posts','posts.created_by','=','users.id')
      ->with('comment')
      ->where('posts.id' ,'=' ,$id)
      ->paginate(10);

Hope this will helpful for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.