Search code examples
phplaraveleager-loading

Laravel Eager Loading Optimization Comments Issue


So I was just messing with the eager loading stuff and I have been checking out how many Sql statements I have been pulling, I really feel what I have here does work but I feel like I could do this in a better way with eager loading. Does anyone have any suggestions or maybe a way to stop each comment from running a query?...

Here Is My Controller function called Show()

public function show($id)
{
    //
    $posts = Post::with(['user','comments'])->where('user_id', $id)->get();

    foreach($posts as $post) {
      echo "<hr /><h2>" . $post->title . "</h2>";
      echo "<p><u style='font-size: 0.8rem;'>By: ". $post->user->name ."</i></u> | <u style='font-size: 0.8rem;'>Date:" . $post->created_at->format('n-j-Y') . "</u>";
      echo "<br />" . $post->content . "</p><hr />";
      echo "<h3>Comments</h3>";
      if($post->comments->isNotEmpty()) {
        foreach($post->comments as $comment) {
          echo "<u>" . $comment->user->name . "</u><br />" . $comment->comment . "<br /><br />";
        }
      } else {
        echo "Sorry there are no comments yet.";
      }
    }
}

Here is the data it pulls and displays on the page I call. Please keep in mind I know I should use a view but I'm mostly doing this for the sake of learning.

select * from posts where user_id = ?

select * from users where users.id in (?)

select comments.*, taggables.post_id as pivot_post_id, taggables.taggable_id as pivot_taggable_id, taggables.taggable_type as pivot_taggable_type from comments inner join taggables on comments.id = taggables.taggable_id where taggables.post_id in (?, ?, ?) and taggables.taggable_type = ?

Posts Web Page:


Bad Ass Title

By: Moriah Mayer | Date:7-30-2018

Deserunt iure recusandae consequatur alias. Et non ratione unde deleniti. Est delectus recusandae consectetur quia tempore. Asperiores ea et voluptas molestias.


Comments

select * from users where users.id = ? limit 1

Julia Mante V

This is a random Post comment hope it works.

select * from users where users.id = ? limit 1

Moriah Mayer

This is another random Post comment hope it works.


New PHP Title

By: Moriah Mayer | Date:7-30-2018

This is our first content ever we created with out a tutorial.


Comments

select * from users where users.id = ? limit 1

Timmothy Fay DDS

That is a interesting post that you have here.


Moriahs Amazing Post

By: Moriah Mayer | Date:7-30-2018

Here we will be showing you what we can do with our mind set to the project there are so many things you can learn from this post.


Comments

Sorry there are no comments yet.


Solution

  • You also need to eager load the user related to each comment. You can eager load nested relationships using dot notation:

    $posts = Post::with(['user', 'comments.user'])->where('user_id', $id)->get();
    

    Now each comment will have its user eager loaded and will not run a new query.