laraveleloquentlaravel-collectionlaravel-pagination

How to use transform in paginated collection in laravel


I want to use map or transform in paginated collection in laravel 5.5 but I am struggling it work

This is what I was trying to do but getCollection is not available in LengthAwarePaginator as what we used to do in previous laravel versions see: How to transform paginated collection

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

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

            return $user;
        });

This is what I receive but there is no pagination details in my result

enter image description here

How can I return transformed collection with pagination details?


Solution

  • I have ended up building custom paginate function in AppServiceProvider

    use Illuminate\Support\Collection;

    In register of AppServiceProvider

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