Ad

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?

Ad

Answer

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,
            ]
        );
    });
Ad
source: stackoverflow.com
Ad