如何在 Laravel 的分页集合中使用变换

The*_*ine 2 laravel eloquent laravel-pagination laravel-collection

我想在 laravel 5.5 中的分页集合中使用 map 或转换,但我正在努力工作

这就是我试图做的,但getCollection不像LengthAwarePaginator我们在以前的 Laravel 版本中所做的那样可用,请参阅:如何转换分页集合

 $query = User::filter($request->all()
        ->with('applications');

    $users = $query->paginate(config('app.defaults.pageSize'))
        ->transform(function ($user, $key) {
            $user['picture'] = $user->avatar;

            return $user;
        });
Run Code Online (Sandbox Code Playgroud)

这是我收到的,但我的结果中没有分页详细信息

在此处输入图片说明

如何返回带有分页详细信息的转换后的集合?

cor*_*eyl 6

对于 Laraval >= 8.x: 如果你想对transform()分页查询构建器结果的集合执行而不是对完整集合进行分页,可以使用以下方法through()

User::filter($request->all()
   ->with('applications')
   ->paginate(config('app.defaults.pageSize'))
   // through() will call transform() on the $items in the pagination object
   ->through(function ($user, $key) {
      $user['picture'] = $user->avatar;

      return $user;
   });

Run Code Online (Sandbox Code Playgroud)


The*_*ine 5

我最终在中构建了自定义分页功能AppServiceProvider

use Illuminate\Support\Collection;

registerAppServiceProvider

 Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
        $page = $page ?: \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPage($pageName);
        return new \Illuminate\Pagination\LengthAwarePaginator(
            $this->forPage($page, $perPage),
            $total ?: $this->count(),
            $perPage,
            $page,
            [
                'path' => \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPath(),
                'pageName' => $pageName,
            ]
        );
    });
Run Code Online (Sandbox Code Playgroud)