Let’s see more about how to paginate the Laravel collection. At Bobcares, with our Laravel Support Services, we can handle your Laravel issues.
How to Paginate Laravel Collection?
The paginate() method in Laravel can be used to paginate the outcomes of database queries. However, if we need to paginate a collection of data that was not acquired directly from a database query, we may do so by calling the paginate() method on the Illuminate\Support\Collection class.
Steps to Paginate Laravel Collection
1. Firstly, create a Laravel collection that contains the data we want to paginate. Using the collect() method will allow us to do this:
$data = [ ['name' => 'John'], ['name' => 'Jane'], // ... more data ]; $collection = collect($data);
2. In order to create a paginated subset of the data, use the collection’s paginate() method. The number of items to show per page and the current page number are the two inputs for this method:
$perPage = 10; // Number of items per page $currentPage = 1; // Current page number $paginatedData = $collection->paginate($perPage, $currentPage);
3. An instance of Illuminate\Pagination\LengthAwarePaginator, which contains both the paginated data and the pagination metadata, will be the outcome of using the paginate() method. Similar to database query pagination, we can also use this paginated data in the views:
foreach ($paginatedData as $item) { // Process each item } // Render pagination links in your view {{ $paginatedData->links() }}
4. Alter the value of the $currentPage variable and execute the paginate() method once more to navigate to a different page of the paginated collection:
$currentPage = 2; $paginatedData = $collection->paginate($perPage, $currentPage);
The pagination is applied after the data is put into memory when using the paginate() function on a collection. Because the full collection must be loaded into memory before pagination can take place, it follows that if we have a huge collection, it might not be the most effective technique to paginate data.
[Need to know more? Get in touch with us if you have any further inquiries.]
Conclusion
If we’re working with huge data and want to take advantage of query pagination, we should think about utilizing the Eloquent query builder or the Query Builder to get the data we need from the database and paginate the results using the paginate() method that is built into the query builder.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
0 Comments