Laravel手动创建分页器


        laravel自带的分页功能十分强大,只不过,在使用 groupBy 语句的分页操作时,无法由 Laravel 有效执行。如果你需要在一个分页结果集中使用groupBy,建议你查询数据库并手动创建分页器。(基于Laravel5.4,老版本可能需要修改个别地方)


默认分页功能示例代码如下:

<?php

 

namespace App\Http\Controllers;

 

use Illuminate\Support\Facades\DB;

use App\Http\Controllers\Controller;

 

class IndexControllerextends Controller

{

   

    publicfunctionindex()

    {

        $person = DB::table('person')->paginate(15);

 

        return view('index.pagTest',['person'=>$person]);

    }

}


手动创建分页器,代码如下;

<?php

namespace App\Http\Controllers\Index;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\LengthAwarePaginator;

class IndexController extends Controller
{
    //测试查询数据库并手动创建分页器
    public function paginationTest(Request $request){
        $perPage = 5;
        $page = $request->input("page",1)-1;
        $total = DB::table("person")
                    ->groupBy()
                    ->count();

        $items = DB::table("person")
                    ->groupBy()
                    ->skip($page*$perPage)
                    ->take($perPage)
                    ->get();

        $person = new LengthAwarePaginator($items, $total,$perPage);
        $person->withPath("pagTest");

        return view("index.paginationTest",['person' => $person]);
    }
}

 

讲解理解LengthAwarePaginator构造函数的前三个参数,就能明白如何手动创建分页器
$person->withPath("pagTest")是设置baseUrl的方法

 

$item             //手动查询到的数据

$total            //所有符合条件的数据总数量

$perPage      //每个页面,数据显示的条数

 

LengthAwarePaginator构造函数,代码如下

/**
 * Create a new paginator instance.
 *
 * @param  mixed $items
 * @param  int $total
 * @param  int $perPage
 * @param  int|null $currentPage
 * @param  array $options (path, query, fragment, pageName)
 * @return void
 */
publicfunction __construct($items,$total,$perPage,$currentPage=null,array$options= [])
{
   
foreach ($optionsas$key=>$value) {
       
$this->{$key} =$value;
    }

   
$this->total=$total;
   
$this->perPage=$perPage;
   
$this->lastPage= (int)ceil($total/$perPage);
   
$this->path=$this->path!='/'?rtrim($this->path,'/') :$this->path;
   
$this->currentPage=$this->setCurrentPage($currentPage,$this->pageName);
   
$this->items=$itemsinstanceofCollection ?$items: Collection::make($items);
}


附上结果图(因为使用了路由,请忽略url的不同:)

Laravel手动创建分页器



相关文章:

  • 2022-01-15
  • 2021-09-01
  • 2021-10-27
  • 2021-09-12
  • 2022-02-07
  • 2022-01-31
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案