marvino's avatar

Get all data from one table and save it to another table using eloquent

I need some help.

I am creating a simple system, How do I get all the data from Table 1 (id, name, address, position, status) which has 2,000+ users, and save/create it all to a new table (table1_id, name, and position, month) using eloquent.

Every time I click the button it will be executed. Thank you. #laravel

0 likes
4 replies
LaryAI's avatar
Level 58

You can use the Eloquent create() method to create a new record in the second table for each record in the first table. You can use the Eloquent all() method to get all the records from the first table.

$table1Records = Table1::all();

foreach ($table1Records as $record) {
    Table2::create([
        'table1_id' => $record->id,
        'name' => $record->name,
        'position' => $record->position,
        'month' => date('m'),
    ]);
}
tisuchi's avatar
tisuchi
Best Answer
Level 70

@marvino Can you check this:

$table1Data = Table1::get();

$table2Data = [];
foreach ($table1Data as $data) {
    $table2Data[] = [
        'table1_id' => $data->id,
        'name' => $data->name,
        'position' => $data->position,
        'month' => now()->format('F'),
    ];
}

Table2::insert($table2Data);
marvino's avatar

@tisuchi

Am I getting the correct Route? cause it's not working

Route::post(billings-save', [BillingController::class, 'save'])->name('billings.save');

and in blade

	<div class="card-body">
              <p>As of <b><?php echo date("F, Y"); ?> </b></p><hr>
              <form action="{{url('billings-save')}}" method="POST">
                <a href="" class="btn btn-primary"><i class="fas fa-print"></i> Generate</a>
              </form>
            </div>
tisuchi's avatar

@marvino You need to submit the form, but you are just using anchor. And ofcourse you need to pass @csrf.

Try this:

<div class="card-body">
  <p>As of <b><?php echo date("F, Y"); ?> </b></p><hr>
  <form action="{{url('billings-save')}}" method="POST">
    @csrf
    <button type="submit" class="btn btn-primary"><i class="fas fa-print"></i> Generate</button>
  </form>
</div>

Please or to participate in this conversation.