Skip to content

Instantly share code, notes, and snippets.

@ramir1
Last active March 19, 2023 19:20
Show Gist options
  • Save ramir1/118c7193e40c67b77435267c6fd06256 to your computer and use it in GitHub Desktop.
Save ramir1/118c7193e40c67b77435267c6fd06256 to your computer and use it in GitHub Desktop.
<?php
/**
* usage in a controlller:
* public function index($page=1) {
* $users = User::paginateUri(5, $page);
* return view('users', compact('users'));
* }
* 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
* Add to model (ex.User):
* use PaginateTrait;
*
* AND in view: $users->linksUri
**/
namespace App\Traits;
use Illuminate\Pagination\Paginator;
Trait PaginateTrait
{
public static function scopePaginateUri($query,$items, $page)
{
$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 = $query->paginate($items);
$links = preg_replace('@href="(.*/?page=(\d+))"@U', 'href="' . str_replace('##', '$2', $current_url) . '"', $paginate->render());
$paginate->linksUri = $links;
return $paginate;
}
}
@reganjohnson
Copy link

This is great - thanks.

@valdineireis
Copy link

HeIlo!
Based on the implementation of @zofe PaginateTrait.php and yours, I adjusted the code to use in Larevel 8, for testing.
valdineireis/iniciando-laravel-8@334d2e1. Thanks.

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