How to insert data from one table to another in laravel?

Member

by lottie , in category: PHP Frameworks , 6 months ago

How to insert data from one table to another in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 2 months ago

@lottie 

To insert data from one table to another in Laravel, you can use Eloquent ORM or Query Builder. Here are two methods to insert data from one table to another:


Method 1: Using Eloquent ORM

  1. Create a model for the table from which you want to insert data (Table A) and another model for the table to which you want to insert data (Table B).
  2. Use the select() method to fetch the data from Table A and then use the create() method to insert the data into Table B.


Example:

1
2
3
4
5
6
7
8
$records = ModelA::select('column1', 'column2')->get();

foreach ($records as $record) {
    ModelB::create([
        'column1' => $record->column1,
        'column2' => $record->column2,
    ]);
}


Method 2: Using Query Builder

  1. Use the DB facade to fetch the data from Table A using select() method and then insert the data into Table B using insert() method.


Example:

1
2
3
4
5
6
7
8
$records = DB::table('table_a')->select('column1', 'column2')->get();

foreach ($records as $record) {
    DB::table('table_b')->insert([
        'column1' => $record->column1,
        'column2' => $record->column2,
    ]);
}


After executing the above code, the data from Table A will be inserted into Table B. Make sure to adjust the column names and table names in the examples based on your database structure.