jlrdw
7 months ago
1470
3
Guides

Paginate collection simple example (Guide)

Posted 7 months ago by jlrdw

Recently the question came up concerning paginating a laravel collection.

This is just a very basic example with a next link, to add a previous link just requires a minus. And a couple of if statements to only show previous if not on page one, same logic for last page. And styles can simply be added using bootstrap and the usage of active and disabled class, simple stuff to do.

Using the example from docs, say you have this in a controller:

   public function colPaginate()
    {
        $page = !empty(Request::input('page')) ? Request::input('page') : '1';
        $perpage = "3";
        $offset = ($page - 1) * $perpage;
        $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
        $slice = $collection->slice($offset, 3);
        return view('testarray.pagcol')
                        ->with('slice', $slice)
                        ->with('page', $page);
    }

And just a simple blade view for demo only

<!DOCTYPE html>
<html lang="en">
    <head>
        
    </head>
    <body>
        @foreach ($slice as $k => $v)
        {{ $v }} </br>
        @endforeach
        
        @php $pageno = $page + 1; @endphp
        <a href="colpage?page={{ $pageno }}">next</a>
    </body>    
</html>

Here first load will default to page 1, and getting 3 at a time:

Hitting next loads next page. Notice the $offset in the controller.

Also there's https://gist.github.com/vluzrmos/3ce756322702331fdf2bf414fea27bcb

For lengthaware example.

Please sign in or create an account to participate in this conversation.