Nervus's avatar

Huge table - how to paginate results

Hello, i want to ask about pagination in laravel. I have middle size table with ~ 5 kk records. I want to use:

$pagination = new LengthAwarePaginator( $collection->forPage($page, $perPage), $collection->count(), $perPage, $page ) As u know first parameter is a collection. I read that I should pass as first param whole eloquent data, then laravel slice those collection to ex. 5 elements (I want see 5 element per page), and then pass result to the view.

Do I understand correctly :

  1. get whole 5 kk records to array or collection
  2. slice them to 5 elements array
  3. put them to the view
0 likes
2 replies
xmarks's avatar

Are you trying to do anything in particular? The method from Laravel documentation is not what you are looking for? So on your Controller you can have:

// This gets all Posts, paginates them by 5
$posts = App\Post::paginate(5);

...

return view('post-view', ['posts' => 'posts']);

Then on the view:

<div class="container">
    @foreach ($posts as $post)
        {{ $post->body }}
    @endforeach
</div>

{{ $posts->links() }} <!-- This is the pagination -->
2 likes
jlrdw's avatar

I read that I should pass as first param whole eloquent data, then laravel slice those collection to ex. 5 elements (I want see 5 element per page), and then pass result to the view.

No

Look at this https://laracasts.com/discuss/channels/guides/length-aware-paginator

Your skip and take comes first, the length aware is only to show the links.

Edit: But as @xmarks stated, you can just use normal pagination in this case.

Please or to participate in this conversation.