0

Let's say I have a Post model that hasMany Comment model. So basically to get the comments I would do $post->comments.

On some websites, I have seen people do this in the controller:

$post = App\Post::with('comments')->findOrFail($id);

return view('someview', compact('post'));

and then inside the view:

@foreach($post->comments as $comment) ...

To my understanding, $post->comments would always have the comments attached and there's no need to call with('comments'). Is this not correct?

If so, then what is the difference between the above and the below:

Controller

$post = App\Post::findOrFail($id);

return view('someview', compact('post'));

View

@foreach($post->comments as $comment) ....

Such Much Code
  • 787
  • 1
  • 9
  • 26
  • With eager loading you get faster response time, And less server load while on the other hand the 2nd approach you'd have what's called N+1 issue where for each row you'll have to run a new query take a look here: http://stackoverflow.com/questions/97197/what-is-the-n1-selects-issue – ahmad Dec 02 '15 at 17:17

1 Answers1

1

It's called Eager Loading: http://laravel.com/docs/5.1/eloquent-relationships#eager-loading

Eager loading will have no affect on your example. Here is a better use case:

$posts = App\Post::orderBy('id')->take(10)->get();

foreach ($posts as $post)
{
    echo $post->comments;
}

Eloquent will create 11 queries to the database which is not good. 1 query to get the posts, and 10 queries to get the comments for each post.

When you eager load your relation(s), Eloquent will only make one other query.

$posts = App\Post::with('comments')->orderBy('id')->take(10)->get();

foreach ($posts as $post)
{
    echo $post->comments;
}

This example will create 2 queries: 1 to get all posts and another to get the posts' comments.

select * from posts

select * from comments where post_id in (1, 2, 3, 4, 5, ...)
Aken Roberts
  • 13,012
  • 3
  • 34
  • 40
Amir Bar
  • 3,007
  • 2
  • 29
  • 47