skip to Main Content

I want to perform insert operations into the database on each pagination page, starting from the first page to the last page, and finish when the last page is done.
but the problem is, I tried this code, but it only loops through 5 data (according to the first pagination), continuously without stopping.

Thanks to anyone who solve my problem.:)

public function __construct()
    {
        $this->data = new Data();
    }
    public function dumData()
    {
        $data = $this->data->paginate(5);
        return $data;
    }

    public function test()
    {
        $page = 1;

        do {
            $dataPaginated = $this->dumData($page);

            $data = $dataPaginated->items();

            foreach ($data as $result) {
                DB::table('test')->insert([
                    'name' => $result->name,
                    'data' => json_encode($result),
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now()
                ]);
            }

            $page++;

            $nextpage = $dataPaginated->nextPageUrl();
        } while ($nextpage);

        return 'success';
    }

2

Answers


  1. Try changing your dumData() method like this:

    public function dumData($pageNumber)
    {
        $data = $this->data->paginate(5, ['*'], 'page', $pageNumber);
        return $data;
    }
    

    Also consider using chunks to fetch the data

    Login or Signup to reply.
  2. Pagination is generally reserved for use on the front-end to display results and provide links to go to the next page. What you’re looking for here is the chunk method which will split your collection every n results.

    Aside from ways to optimise this, the following structure you want to follow is:

    $chunks = $collection->chunk(5);
    foreach ($chunks as $chunk) {
       foreach ($chunk as $item) {
           //Insert here
       }
    } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search