1.在App\Service新建一个service 继承 LengthAwarePaginator (也可以写在其他层次)
<?php
namespace App\Service;
class LengthAwarePaginatorService extends \Illuminate\Pagination\LengthAwarePaginator
{
/**
* 重写toArray
**/
public function toArray()
{
return [
'data' => $this->items->toArray(),
'total' => $this->total(),
'currentPage'=>$this->currentPage(),
];
}
/**
* 添加一个object转数组的方法
* 处理生成新的分页
**/
public function pageInit(){
$total = $this->total();
$limit=$this->perPage();
$page = $this->currentPage();
$list = $this->items();
if (empty($total)){
return ['total'=>0,'pages'=>1,'next_page'=>0,'lists'=>[]];
}
$pages=(int)ceil($total/$limit);
$next_page = 0;
if($page<$pages){
$next_page = ++$page;
}
return ['total'=>$total,'pages'=>$page,'pageSize' => $limit,'next_page'=>$next_page,'list'=>$list];
}
}
2.在/app/Providers/AppServiceProvider.php中注册一下
主要是在register方法里面
<?php
namespace App\Providers;
use App\Services\LengthAwarePaginatorService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->bind('Illuminate\Pagination\LengthAwarePaginator',function ($app,$options){
return new LengthAwarePaginatorService($options['items'], $options['total'], $options['perPage'], $options['currentPage'] , $options['options']);
});
}
}