Laravel 5 - Manual pagination

2019-01-07 21:17发布

问题:

Pagination::make() method doesn't exist in Pagination class anymore in Laravel 5.

Is there a workaround to make manual pagination work in Laravel 5?

回答1:

You need to add use:

use Illuminate\Pagination\LengthAwarePaginator as Paginator;

and now you can use:

 $paginator = new Paginator($items, $count, $limit, $page, [
            'path'  => $this->request->url(),
            'query' => $this->request->query(),
        ]);

to get data in the same format as paginating on model object;



回答2:

You can create manual pagination like this

$data = DB::table('post')->skip(0)->take(20)->get();



回答3:

Pretty way to instance this class

 use Illuminate\Pagination\LengthAwarePaginator as Paginator;
 //...
 $paginator = new Paginator($items->forPage($page, $limit), $count, $limit, $page, [
            'path'  => Paginator::resolveCurrentPath()
        ]);

Note items must be a Collection Object.



回答4:

Try below code for manual pagination

<?php

namespace App\Http\Controllers;

use Illuminate\Pagination\LengthAwarePaginator as Paginator;
// use Illuminate\Pagination\Paginator;
use Illuminate\Http\Request;
use App\Product;
class MyController extends Controller
{
    public function index(Request $request){
        $items = Product::all();

        $filter_products = []; // Manual filter or your array for pagination

        foreach($items as $item){
            if($item['id']>40 && $item['id']<50){
                array_push($filter_products, $item);
            }
        }

        $count = count($filter_products); // total product for pagination
        $page = $request->page; // current page for pagination

        // manually slice array of product to display on page
        $perPage = 5;
        $offset = ($page-1) * $perPage;
        $products = array_slice($filter_products, $offset, $perPage);

        // your pagination 
        $products = new Paginator($products, $count, $perPage, $page, ['path'  => $request->url(),'query' => $request->query(),]);
        // use {{ $products->appends($_GET)->links() }} to dispaly your pagination
        return view('index',['products' => $products]);
    }
}


回答5:

Another way of using pagination would be like this:

public function index()
{
    $posts = DB::table('posts')->paginate(15);
}