Such Much Code
Such Much Code

Reputation: 827

Eloquent model 'with' call inside the controller

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

Upvotes: 0

Views: 1062

Answers (1)

Amir Bar
Amir Bar

Reputation: 3105

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, ...)

Upvotes: 1

Related Questions