laravel自定义分页

当斧头来到树林里的时候,好多树都说,至少它的把手是我们自己人。
Let’s say that you have an array of data, e.g results from a search query, and you want to paginate them.

Laravel provides pagination for Eloquent results out of the box, but for custom data we need to do the pagination manually.

Let see how in the next example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?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]);
}
?>

Now in the view add the following:

1
2
3
4
5
@foreach ($results as $result)
<p>{{ $result }}</p>
@endforeach

<?php echo $results->render(); ?>

http://psampaz.github.io/custom-data-pagination-with-laravel-5/