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']);
        });
    }

格式化输出的结果示例

posted @ 2021-04-10 11:26  以己为镜  阅读(710)  评论(0编辑  收藏  举报