How to paginate a collection after get() in Laravel?

user7432810 picture user7432810 · Apr 18, 2017 · Viewed 7.8k times · Source

I have a merge on two query results which works fine:

$events1 = \App\Event::Where('valid_to','>=',$today)->orderByRaw('valid_to','ASC')->get();
$events2 = \App\Event::Where('valid_to','<',$today)>orderByRaw('valid_to','ASC')->get();
$events = $events1->merge($events2); 

Now I need to paginate this new collection and as suggestted I added this piece:

$page = 1;
$perPage = 60;
$pagination = new \Illuminate\Pagination\LengthAwarePaginator(
    $events->forPage($page, $perPage), 
    $events->count(), 
    $perPage, 
    $page
);

EDIT: For future readers, patricus's answer works great and I did that.

Answer

Rohallah Hatami picture Rohallah Hatami · May 15, 2019

best way for paginate collection:

1- add this to boot function in \app\Providers\AppServiceProvider

  /**
         * Paginate a standard Laravel Collection.
         *
         * @param int $perPage
         * @param int $total
         * @param int $page
         * @param string $pageName
         * @return array
         */
        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,
                ]
            );
        });

2-From hereafter for all collection you can paginate like this

$events1 = \App\Event::Where('valid_to','>=',$today)->orderByRaw('valid_to','ASC')->get();
$events2 = \App\Event::Where('valid_to','<',$today)>orderByRaw('valid_to','ASC')->get();
$events = $events1->merge($events2); 

$events->paginate(5)