Laravel Paginator for Collections or Arrays
Make the pagination for arrays or Collections, (*1)
``` bash $ composer require amamarul/laravel-paginator, (*2)
### Add Provider into config/app.php ``` php Amamarul\Paginator\PaginatorServiceProvider::class,
``` php use Amamarul\Paginator\Paginator; use Illuminate\Http\Request;, (*3)
public function index(Request $request) { $currentPage = isset($request['page']) ? (int) $request['page'] : 1; $perPage = 1; $path = $request->path();, (*4)
$items = array_map(function ($value) { return [ 'name' => 'User #' . $value, 'url' => '/user/' . $value, ]; }, range(1,1000)); $paginator = new Paginator($items); $paginator = $paginator->paginate($currentPage,$perPage, $path); return view('index')->with('paginator', $paginator);
}, (*5)
- Collection ``` php use App\User; use Amamarul\Paginator\Paginator; use Illuminate\Http\Request; public function index(Request $request) { $currentPage = isset($request['page']) ? (int) $request['page'] : 1; $perPage = 1; $path = $request->path(); $items = User::with('profile')->get()->sortBy('profile.name'); $paginator = new Paginator($items); $paginator = $paginator->paginate($currentPage,$perPage, $path); return view('index')->with('paginator', $paginator); }
``` php @foreach ($paginator->items() as $element) , (*6)
@endforeach, (*7)
{!! $paginator->render() !!} ```, (*8)
By default the url has page
name
http://127.0.0.1:8000/?page=3
If you´d like to change the page name yo must only add a fourth parameter with the name.
Like this, (*9)
``` php use App\User; use Amamarul\Paginator\Paginator; use Illuminate\Http\Request;, (*10)
public function index(Request $request) { $currentPage = isset($request[$pageName]) ? (int) $request[$pageName] : 1; $perPage = 1; $path = $request->path(); $pageName = 'custom-name';, (*11)
$items = User::with('profile')->get()->sortBy('profile.name'); $paginator = new Paginator($items); $paginator = $paginator->paginate($currentPage,$perPage, $path, $pageName); return view('index')->with('paginator', $paginator);
} ```, (*12)
Created by Maru Amallo-amamarul, (*13)