很多时候查询结果需要用 Collection 处理后再分页,而 Laravel 中是不支持的。
下面稍作修改,来实现上面的需求
$users = DB::table('users')
->get()
->each(function($item, $key){
$item->total = 11;
})->paginate(15);
app/Providers/AppServiceProvider.php
文件,头部引入下面类use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
boot 方法中添加以下代码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('');
});
}
再去测试,发现分页又回来了。