phoennix's avatar

Pagination after a sortBy on Eloquent

Hello,

I'm trying to paginate within an Eloquent but impossible request, I always get an error telling me that paginate() or simplePaginate() doesn't exist.

$selectedInterviews = Company_Interview::all()->sortBy(function ($temp, $key) {
            return Carbon::parse($temp['interview_date'] . ' ' . $temp['start_time'])->getTimestamp();
        });

Do you have an idea of the problem ?

Thanks :)

0 likes
2 replies
jonathan-voxie's avatar

The sortBy return Illuminate\Support\Collection for this reason you cannot use paginate or simplePaginate.

1 like
MichalOravec's avatar
Level 75

@phoennix Add this to your app/Providers/AppServiceProvider.php to the boot method

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

public function boot()
{
    Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
        $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);

        return new LengthAwarePaginator($this->forPage($page, $perPage), $total ?: $this->count(), $perPage, $page, [
            'path' => LengthAwarePaginator::resolveCurrentPath(),
            'pageName' => $pageName,
        ]);
    });
}

Then you can use pagination on a collection.

$selectedInterviews = Company_Interview::all()->sortBy(function ($temp, $key) {
    return Carbon::parse($temp['interview_date'] . ' ' . $temp['start_time'])->getTimestamp();
})->paginate(15);
2 likes

Please or to participate in this conversation.