In this episode, we're tackling a slightly uncommon scenario: paginating a Laravel collection (not a database query). Normally, you'd use Laravel's built-in pagination on queries, letting the database do the heavy lifting. But sometimes, like when pulling data from flat files into a collection, we need to paginate after we've already got all the data in memory.
You'll see how to create a custom pagination macro for Laravel collections. We start by exploring what a macro is in Laravel, which lets us add new methods (like paginate
) directly onto the collection class. We'll add our macro inside a service provider, keeping it close to our app logic.
The macro takes care of all the usual pagination stuff: figuring out which items belong on the current page using the forPage
method, keeping track of the total number of items, how many to show per page, and which page we're on. We also wire it up so the current page can come from the query string, exactly how Laravel typically works.
By the end, you'll have a neat way to paginate any Laravel collection, mimicking the familiar query builder behavior, complete with support for specifying the current page and items per page. Next up, you'll see how to actually show those pagination links to users!