Skip to content

Instantly share code, notes, and snippets.

@phamngsinh
Created July 26, 2016 10:24
Show Gist options
  • Select an option

  • Save phamngsinh/efa48dc0bc38d1271fd03c6b2f7f13cf to your computer and use it in GitHub Desktop.

Select an option

Save phamngsinh/efa48dc0bc38d1271fd03c6b2f7f13cf to your computer and use it in GitHub Desktop.
Custom data pagination with Laravel 5
<?php namespace App\Http\Controllers;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
class SearchController extends Controller {
public function search()
{
.
.
.
$searchResults = [
'item1',
'item2',
'item3',
'item4',
'item5',
'item6',
'item7',
'item8',
'item9',
'item10'
];
//Get current page form url e.g. &page=6
$currentPage = LengthAwarePaginator::resolveCurrentPage();
//Create a new Laravel collection from the array data
$collection = new Collection($searchResults);
//Define how many items we want to be visible in each page
$perPage = 5;
//Slice the collection to get the items to display in current page
$currentPageSearchResults = $collection->slice($currentPage * $perPage, $perPage)->all();
//Create our paginator and pass it to the view
$paginatedSearchResults= new LengthAwarePaginator($currentPageSearchResults, count($collection), $perPage);
return view('search', ['results' => $paginatedSearchResults]);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment