Laravel 5 - Manual pagination

半城伤御伤魂 提交于 2019-11-26 11:18:12

问题


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:


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.




回答3:


You can create manual pagination like this

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




回答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);
}


来源:https://stackoverflow.com/questions/27213453/laravel-5-manual-pagination

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!