Laravel 5.4 LengthAwarePaginator Laravel 5.4 LengthAwarePaginator laravel laravel

Laravel 5.4 LengthAwarePaginator


When manually creating a paginator, you have to slice the result set yourself. The first parameter to the paginator should be the desired page of results, not the entire result set.

From the pagination documentation:

When manually creating a paginator instance, you should manually "slice" the array of results you pass to the paginator. If you're unsure how to do this, check out the array_slice PHP function.

I would suggest using a Collection to help out with this a little:

// ...$collection = collect($collection);$page = 1;$perPage = 10;$paginate = new LengthAwarePaginator(    $collection->forPage($page, $perPage),    $collection->count(),    $perPage,    $page,    ['path' => url('api/products')]);


For the heavy select and to avoid any multiple select to calculate the total from the table we unable to use model paginate

use Illuminate\Pagination\LengthAwarePaginator;

in your controller function

if(!isset($input["total"])){ //initial request         $total = //Find the total only one time.         $request->request->add(['total' => $total]); //Add it in the request so that we can print it in blade }else         $total = $input["total"];  //After initial request$currentPage = LengthAwarePaginator::resolveCurrentPage(); //page variable from GET or POST$perPage = 30; //Page Length $offset = ($currentPage - 1) * $perPage; //find the offset to pass in query$specificRecords = /*Collect specific page records in array if mysql then Select * from table limit $perPage offset $offset if ms sql then OFFSET {$offset} ROWS FETCH NEXT {$perPage} ROWS ONLY */$records = new LengthAwarePaginator($specificRecords,$total,$perPage,Null,[ "path" => "/pagepath" ]);

in blade:

<center>{{$records->appends(Request::except([ 'page','_token' ]))->links()}}</center>

Check Page and total variable in page tags ensure you added page in except list :)