Skip to content

Instantly share code, notes, and snippets.

@zofe
Last active March 19, 2019 20:30
Show Gist options
  • Save zofe/ced0054e6ac6eff1ea95 to your computer and use it in GitHub Desktop.
Save zofe/ced0054e6ac6eff1ea95 to your computer and use it in GitHub Desktop.
switch laravel 5 pagination from QueryString To URI, using simple traits on models
<?php
/**
* usage in a controlller:
* public function index($page=1) {
* $users = User::paginateUri(5, $page, $links);
* return view('users', compact('users','links'));
* }
* it also support variable number of parameters,
* routes must be defined using {page} or {page?} placeholders
* $links is returned as reference and contain a standard bootstrap 3 navigation
**/
namespace App\Pagination;
use Illuminate\Pagination\Paginator;
Trait PaginateTrait {
public static function paginateUri($items, $page, &$links) {
$action = app('request')->route()->getActionName();
$parameters = app('request')->route()->parameters();
$parameters['page'] = '##';
$current_url = action(str_replace('App\Http\Controllers\\','',$action), $parameters);
Paginator::currentPageResolver(function() use ($page) { return $page; });
$paginate = self::paginate($items);
$links = preg_replace('@href="(.*/?page=(\d+))"@U', 'href="'.str_replace('##','$2', $current_url).'"',$paginate->render());
return $paginate;
}
}
@Vongsi
Copy link

Vongsi commented Apr 8, 2016

Hi Zofe

This is an interesting solution, but how can I use it in our controller? Do we need to define $links as a variable before send through the method paginateUri?

I tried it but got below error message

Call to undefined method Illuminate\Database\Query\Builder::paginateUri()

Thanks

@fmimolu
Copy link

fmimolu commented Apr 18, 2016

Hi Zofe ,
I also have the same problem as Vongsi . You could tell how to fix it . An example?
Thank you

@zofe
Copy link
Author

zofe commented May 30, 2016

sorry.. i missed comments here:
@Vongsi no you don't need to instance $links, it's just returned as reference and contain the overridden navigation links

if you got an error is just because you're not applyng the trait on your models.. In the example i missed to show that User model use the PaginationTrait:

class User extends Model    {
    use PaginateTrait;
   ...

So you should add the trait on each model you want to paginate via URI (and you should adapt your routes don't miss this)

This is tested and in production on a L5.1 but should work also on L5.*

@ramir1
Copy link

ramir1 commented Mar 16, 2019

I modifed your code and use in laravel 5.7:
https://gist.github.com/Ramir1/118c7193e40c67b77435267c6fd06256

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment