Skip to content

Instantly share code, notes, and snippets.

@lantrinh1999
Forked from mzaman/Custom.txt
Created April 29, 2021 03:20
Show Gist options
  • Save lantrinh1999/9ea4229bf4d71806be97a9b635a4fe39 to your computer and use it in GitHub Desktop.
Save lantrinh1999/9ea4229bf4d71806be97a9b635a4fe39 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