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); }
Guys, method paginate() doesnt work with collections. You can not paginate the collection but you can subdivide it with the method chunk of collection.
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/…
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.
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
Collection forPage(int $page, int $perPage)
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With