How to loop over each page in laravel paginator

Viewed 302

I've used laravel pagination to retrieve data from a table, I'm able to get the items of the first page but how to loop over each page and get the items from each page

Here is my code

public function handle()
{
    $productsInstance = Products::query()->paginate(10);
    $totalPages = $productsInstance->lastPage();

    for ($i=1; $i <= $totalPages; $i++) {
        foreach ($productsInstance as $productInstance) {
            $items = $productInstance->items;

            foreach ($items as $item) {
                // operation performed on each item
            }
        }
    }
}

The products table I'm querying and paginating is having a record of more than 200k, I'm able to perform the foreach operation on the first page but how to get items from each page

1 Answers

You should install QueryFilter package & use that package reference in your Model

  1. Create Product Model and use App\Filters\QueryFilter;

  2. Next in Product Model use below function

    /* scope for filters */

    public function scopeFilter($query, QueryFilter $filters)

    {

    return $filters->apply($query);
    

    }

  3. In Controller or Jobs

    $limit = request()->limit ?? 10;

    $products = Product::filter($filter)->paginate($limit);

  4. Route should be to get products-> /api/products?limit=10&page=1

Related