search

Home  >  Q&A  >  body text

How to loop through the page and insert data using Laravel

<p>I want to perform an insert into the database on each paginated page, starting from the first page and ending with the last page, until the last page is completed. But the problem is, I tried this code, but it only loops through 5 pieces of data (based on the first pagination) and keeps going. </p> <p>Thanks to anyone who solves my problem. :)</p> <pre class="brush:php;toolbar:false;">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'; }</pre> <p><br /></p>
P粉282627613P粉282627613530 days ago697

reply all(1)I'll reply

  • P粉642920522

    P粉6429205222023-08-16 17:41:36

    Try changing your dumData() method to the following:

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

    You can also consider using chunks to obtain data

    reply
    0
  • Cancelreply