Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I paginate a merged collection in Laravel 5?

I am creating a stream which contains two types of objects, BluePerson and RedPerson. To create the stream, I fetch all of both objects, then merge them into one collection. After doing so, I need to paginate them, however paginate is for eloquent models and DB queries, and not collections, it seems. I have seen a lot about manually creating a paginator, but the documentation, especially in the API is sparse (I can't even seem to find the arguments the Paginator class accepts.)

How can I paginate the results of merging my collections?

public function index() {     $bluePerson = BluePerson::all();     $redPerson = RedPerson::all();      $people = $bluePerson->merge($redPerson)->sortByDesc('created_at');       return view('stream.index')->with('people', $people); } 
like image 891
KinsDotNet Avatar asked May 24 '15 05:05

KinsDotNet


People also ask

Can you paginate a collection in Laravel?

Guys, method paginate() doesnt work with collections. You can not paginate the collection but you can subdivide it with the method chunk of collection.

How can we manually create pagination in Laravel?

Just to say (Laravel doc): When manually creating a paginator instance, you should manually "slice" the array of results you pass to the paginator. Could you explain parameters please? The parameters are discussed over the construct method: laravel.com/api/5.0/Illuminate/Pagination/…

How can I get pagination page numbers in Laravel?

In your case you can use $articles->links() in your view to generate the pagination navigation buttons. But if you want to manually set the page then you can do this. $articles = Articles::paginate(5, ['*'], 'page', $pageNumber); The default paginate method takes the following parameters.


1 Answers

however paginate is for eloquent models and DB queries, and not collections, it seems.

You are right. but there is ineed a paginator function for collections. forPage

Syntax:

Collection forPage(int $page, int $perPage) 

Example:

Rest is simple.

public function foo() {     $collection = collect([1,2,3,4,5,6,7,8,9,0]);     $items = $collection->forPage($_GET['page'], 5); //Filter the page var     dd($items); } 
like image 82
itachi Avatar answered Oct 02 '22 17:10

itachi