Laravel Collection分页

很多时候查询结果需要用 Collection 处理后再分页,而 Laravel 中是不支持的。
下面稍作修改,来实现上面的需求

  1. 集合处理查询结果
    $users = DB::table('users')
            ->get()
            ->each(function($item, $key){
                $item->total = 11;
            })->paginate(15);
    
  2. 分页加入服务提供者中
    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('');
                });
        }
    
    再去测试,发现分页又回来了。

猜你喜欢

转载自blog.csdn.net/qq_42094066/article/details/105372207