Laravel 5 Manual Pagination Filter Results

This is the result showing 10 items per page:

Laravel 5 Manual Pagination Filter Results


  • Setup manual pagination because I need to grab a count of model relationship rows
  • Add the model relation count to the paginated model so the counts can be displayed on the page
  • Make use of Laravel 5’s awesome bootstrap pagination to switch between pages
  • Optionally cache the results

After a lot of coding different ways and researching on different forums, particularly laracasts, there was nothing which worked fully, only partly. This is how I got it all working.

//get the count for each item and sort by count, offset to pagination page number
$pageTags = Tag::selectRaw(‘tags.*, count( AS count‘)
->leftJoin(DB::raw(‘(select * from module_tag) as mods’),’’, ‘=’, ‘mods.tag_id’)
->offset(($page-1) * $numPerPage)

//manually create a new pagination object to pass to the blade view
$data[“tags”] = new Paginator($pageTags, $total, $numPerPage, $page, array(“path” => ‘/tags’));

See it in action:

pagination in action

Another attempt which didn’t quite make it.

1. get all tags
2. append counts to all tags
3. sort by count
4. create a pagination

$tags = $tags->each(function($tag)
$moduleTags = DB::table(“module_tag”)->selectRaw(“id, count(*) as count”)->where(“tag_id”, $tag->id)->first();
$tag->count = $moduleTags->count;

$tags->sort(function($a, $b) {
$a = $a->count;
$b = $b->count;
if ($a === $b) {
return 0;
return ($a < $b) ? 1 : -1; }); //4 $page = (Input::get(‘page’)) ? Input::get(‘page’) : 1; $data[“tags”] = new Paginator($tags->all(), count($tags), 10, $page);

Sam Deering is a web developer from England (currently living in Australia). In his spare time he enjoys coding, playing chess, reading and investing.

One thought on “Laravel 5 Manual Pagination Filter Results

  1. The ‘count($tags)’ of the last attempt may not give the right count of items, try this instead: count((array)$tags)

Leave a Reply

Your email address will not be published. Required fields are marked *