laravel重新封装paginate分页返回数据
参客:林明潭blog
定义目录
- 在
app\Services
中定义ApplySerializePaginate.php
<?php
namespace App\Services;
use Illuminate\Pagination\LengthAwarePaginator;
class ApplySerializePaginate extends LengthAwarePaginator
{
/**
* @return array
* @usage
* 格式化数据:(格式化回调)
$paginate->toArray(function($item){$item['nickname']='张三';});
*
* 格式化数据:(原始方法)
$paginate = User::query()->paginate();
$paginate->getCollection()->transform(function ($model) {
return $model;
});
*/
public function toArray()
{
return [
'data' => $this->items->toArray(),
'total' => $this->total(),
'pageSize'=>(int)$this->perPage(),
'page'=>$this->currentPage(),
];
}
或者
public function toArray(callable $formatter=null)
{
return [
'data' => $formatter ? ($this->items->each($formatter)->toArray()) : $this->items->toArray(),
'total' => $this->total(),
'pagesize' => (int)$this->perPage(),
'page' => $this->currentPage(),
];
}
}
- 在
app\Providers
文件下的AppServiceProvider.php
中的register
方法中定义
use App\Services\ApplySerializePaginate;
public function register()
{
//
$this->app->bind('Illuminate\Pagination\LengthAwarePaginator',function ($app,$options){
return new ApplySerializePaginate($options['items'], $options['total'], $options['perPage'], $options['currentPage'] , $options['options']);
});
}
格式化输出的结果示例