很多时候查询结果需要用 Collection 处理后再分页,而 Laravel 中是不支持的。
下面稍作修改,来实现上面的需求
- 集合处理查询结果
$users = DB::table('users') ->get() ->each(function($item, $key){ $item->total = 11; })->paginate(15);
- 分页加入服务提供者中
在app/Providers/AppServiceProvider.php
文件,头部引入下面类
boot 方法中添加以下代码use Illuminate\Pagination\Paginator; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection;
再去测试,发现分页又回来了。if (!Collection::hasMacro('paginate')) { Collection::macro('paginate', function ($perPage = 15, $page = null, $options = []) { $page = $page ?: (Paginator::resolveCurrentPage() ?: 1); return (new LengthAwarePaginator( $this->forPage($page, $perPage), $this->count(), $perPage, $page, $options)) ->withPath(''); }); }