Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

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

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

$events1 = AppEvent::Where('valid_to','>=',$today)->orderByRaw('valid_to','ASC')->get();
$events2 = AppEvent::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 IlluminatePaginationLengthAwarePaginator(
    $events->forPage($page, $perPage), 
    $events->count(), 
    $perPage, 
    $page
);

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

best way for paginate collection:

1- add this to boot function in appProvidersAppServiceProvider

  /**
         * 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 = AppEvent::Where('valid_to','>=',$today)->orderByRaw('valid_to','ASC')->get();
$events2 = AppEvent::Where('valid_to','<',$today)>orderByRaw('valid_to','ASC')->get();
$events = $events1->merge($events2); 

$events->paginate(5)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...