Search code examples
phplaravellaravel-5laravel-5.3

laravel eloquent nested SELECT statement


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.


Solution

  • 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.