Paginators in Laravel

Posted: February 15, 2017 19:23 | By: serge

Laravel paginator documentation is a little short, especially with creating/paginating manually... In case you wondered, here is a brief overview of how they work how to make them work...

No magic, paginators will call your controller function for every page. The request will have the pagination information in it. It is your job to actually select and slice the page. The paginator simply presents it... which is a big part of the work... 

Let's take a look at a simple comment display controller function as an example... Displays a list of comments from a database query... 

public function comments(){

    // DB::select returns an array, thus we have to build the paginator ourselves...
    $comm = DB::select('select bla bla bla from comments where this and that... 
                        order by approved ASC');

    // this basically gets the request's page variable... or defaults to 1
    $page = Paginator::resolveCurrentPage('page') ?: 1;

    // Assume 15 items per page... so start index to slice our array
    $startIndex = ($page - 1) * 15;

    // Length aware paginator needs a total count of items... to paginate properly
    $total = count($comm);

    // Eliminate the non relevant items...
    $results = array_slice($comm, $startIndex, 15);

    $comments =  new LengthAwarePaginator($results, $total, 15, $page, [
        'path' => Paginator::resolveCurrentPath(),
        'pageName' => 'page',
    ]);
    return view('backend/comments', compact('comments'));
}

As you can see it's pretty simple once you have figured it out... works just dandy. The key is you have to prepare the data slice yourself... 

 

 

 

 


Welcome


Hi, my name is Serge Lachapelle, a nerdy entrepreneur from Montreal, Canada. I love tech, startups, business and freedom in general. I share my experiences here as I re-invent the way I work. Let's connect and create something cool...

Subscribe to new posts



Categories

Laravel 3

LIfe 1

Programming 4

Startup 1

Technology 1

VueJS 1

Recent Posts

Resources

Laravel the source of all the awsomeness...

Laracast well worth the money, great training...

VueJS simple and logical javascript framework...

About

This is my personal blog. I decided to share my journey as I re-invent the way I work. I figured that other older programmers and entrepreneurs would share this quest to return to understanding the mechanics in order to reboot our creativity. I would be delighted if you followed my ramblings on Twitter or connect on LinkedIn...

Social Links

Location

I live in,
Montreal, Quebec
Canada.