使用方式
主要是用到了类的重写和容器
$users = DB::table('users')->paginate(15);

{
"code": 200,
"data": {
"current_page": 1,
"data": [
{
"id": 1,
"name": "技术部",
"description": "",
"qr_code_path": "http://mag.com/1.jpg",
"created_at": "2020-06-24 16:12:43",
"updated_at": "2020-06-24 16:12:44"
}
],
"first_page_url": "http://mag.com/department?page=1",
"from": 1,
"last_page": 1,
"last_page_url": "http://mag.com/department?page=1",
"next_page_url": null,
"path": "http://mag.com/department",
"per_page": 10,
"prev_page_url": null,
"to": 1,
"total": 1
},
"message": "success"
}
查看文件
laravel5\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Builder.php
paginate
paginator
public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
{
$page = $page ?: Paginator::resolveCurrentPage($pageName);
$perPage = $perPage ?: $this->model->getPerPage();
$results = ($total = $this->toBase()->getCountForPagination())
? $this->forPage($page, $perPage)->get($columns)
: $this->model->newCollection();
return $this->paginator($results, $total, $perPage, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => $pageName,
]);
}
跟进:laravel5\vendor\laravel\framework\src\Illuminate\Database\Concerns\BuildsQueries.php

可以看到我用红色标出来是是返回的分页类, 用蓝色标出来是用容器加载的这个类。
继续查找这个类 laravel5\vendor\laravel\framework\src\Illuminate\Pagination\LengthAwarePaginator.php
发现组装分页数据的是这个类中toArray
方法
public function toArray()
{
return [
'current_page' => $this->currentPage(),
'data' => $this->items->toArray(),
'first_page_url' => $this->url(1),
'from' => $this->firstItem(),
'last_page' => $this->lastPage(),
'last_page_url' => $this->url($this->lastPage()),
'next_page_url' => $this->nextPageUrl(),
'path' => $this->path,
'per_page' => $this->perPage(),
'prev_page_url' => $this->previousPageUrl(),
'to' => $this->lastItem(),
'total' => $this->total(),
];
}
刚刚上面也说这个分页类是通过容器加载的,那我们只要在容器内重新加载下这个类就行。
修改方式
先自定义一个分页类,继承上面的分页类,并重写了toArray
方法。
新建文件夹及类文件
laravel5\app\Services\Common\LengthAwarePaginatorService.php
namespace App\Services\Common;
class LengthAwarePaginatorService extends \Illuminate\Pagination\LengthAwarePaginator
{
public function toArray()
{
return [
'data' => $this->items->toArray(),
'total' => $this->total(),
];
}
}
然后在 laravel5\app\Providers\AppServiceProvider.php
容器内重新绑定了这个分页类的实现
<?php
namespace App\Providers;
use App\Services\Common\LengthAwarePaginatorService;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
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']);
});
}
public function boot()
{
\Schema::defaultStringLength(191);
}
}
预览
