P
P
photosho2016-01-12 14:24:29
Laravel
photosho, 2016-01-12 14:24:29

How to correctly pass data to the display?

Hello. Let's say you want to display a list of all blog articles. I create a controller action:

$posts = Post::all()->toArray();
return view('posts', ['posts' => $posts]);

And further, in display, through "foreach" I deduce the list of articles.
But the Eloquent documentation says that if there are too many elements, a simple "foreach" can waste all the RAM traversing them. It is suggested to use the following code:
User::chunk(200, function($users) {
    foreach ($users as $user) {
        //
    }
});

How to use the "chunk" method in the view, if, as I understand it, it should be completely decoupled from the model? That is, "chunk" is a method of the "Post" model, but writing in the mapping use App\Post;and using the methods of the model is hardly the right solution.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Ukolov, 2016-01-12
@photosho

Personally, I don't see anything wrong with using objects in the View. What do you gain by casting an object to an array? Are you unbinding the template from the model? Pretty dubious benefits, but the problems are obvious.
There is a very detailed discussion here .
To answer your question, it should be like this:

$posts = Post::all();
return view('posts', ['posts' => $posts]);

$posts->chunk(200, function($chunk) {
    foreach ($chunk as $post) {
        //
    }
});

And if you do it right, then you don’t need to display everything on one page and use pagination. Then the problem with memory will be solved by itself.

D
D', 2016-01-12
@Denormalization

In fact, the problem is contrived.
What is your goal by displaying > 200 objects on a page?
Why not just use the paginate method and paginate the results? Then there will be no problem with over9000 objects on the page.

S
Stanislav Pochepko, 2016-01-12
@DJZT

Displayed 500 users per page with 8 fields, 3 of which are relationships. (Role, Group, Number of posts), but at the same time I used the method in the controller User->with('role')and did not notice anything. Limit in PHP is 384MB

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question