Let's talk about pagination for products. Now, on the home page, we have all the products loaded, which, in this case, is twenty products. But in the real world, shops could have hundreds and thousands of products. So we need to paginate them.
In a regular Laravel project, instead of using get()
, you would use paginate()
.
app/Http/Controllers/Api/ProductController.php:
class ProductController extends Controller{ public function index() { $products = Product::with('category')->get(); $products = Product::with('category')->paginate(9); return ProductResource::collection($products); }}
And in the Blade, you would do $products->links()
, and it would generate the pagination with links.
But in the API, we work only with the data. How do we tell the frontend the links for the pagination, how many records are there, how many pages, and what the next and previous pages are? When using Resources and returning a collection, Laravel handle...