How to loop through the page and insert data using Laravel
P粉282627613
2023-08-15 21:39:21
<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>
Try changing your dumData() method to the following:
You can also consider using chunks to obtain data