How to copy existing table in Laravel?
Asked Answered
A

4

7

I want to know how to copy existing table in Laravel? I am new to Laravel. I am trying to make an online exam application. I want to create a table for each user and copy all the contents of the exam table to this newly created table.

This is the script that I wanted to do. It works fine when not in laravel. What is the laravel way to do this?

$check = mysql_query("CREATE TABLE IF NOT EXISTS ".$testname." ( id INT, user VARCHAR(30), questn VARCHAR(30), ans VARCHAR(30))");

mysql_query ("INSERT IGNORE INTO ".$testname." SELECT * FROM test");
Adynamia answered 31/3, 2014 at 13:29 Comment(1)
Post is as an answer if it works, it's not helpful for others in a comment, doesn't look clear.Coruscation
B
17

You can duplicate a DB table in Laravel using the DB::statement method like this:

\DB::statement('CREATE TABLE new_table LIKE old_table');
\DB::statement('INSERT new_table SELECT * FROM old_table');

This will duplicate the structure, indexes and data of old_table to new_table.

Blanche answered 3/9, 2018 at 16:32 Comment(1)
Is there a faster way, to just copy table and not by doing inserts?Hydroquinone
A
2

Here is the solution (Someone helped me to solve this):

$db = DB::connection(); 

$sql = "CREATE TABLE IF NOT EXISTS ".$testname." ( id INT, user VARCHAR(30), questn VARCHAR(30), ans VARCHAR(30))"; 
$db->statement($sql); 

$sql = "INSERT IGNORE INTO ".$testname." SELECT * FROM test"; 
$db->statement($sql);
Adynamia answered 31/3, 2014 at 21:51 Comment(1)
You can except your answer :-)Coruscation
P
1
$user = DB::connection('mysql')->select('select * from usersdata');

foreach ($user as $record) {
    $user = DB::connection('mysql1')->table("tablename")->insert(get_object_vars($record));
Porker answered 5/8, 2016 at 7:23 Comment(1)
Why should the OP "try this"? A good answer will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO that may find this question and be reading your answer.Confederacy
C
1

You can duplicate the table structure and data by the following

use Illuminate\Support\Facades\DB;

if (!Schema::hasTable('new_table_name')) { // make sure table does not exists already
    // creates table structure
    DB::statement('CREATE TABLE new_table_name LIKE old_table_name');
    //inserts table data
    DB::statement('INSERT new_table_name SELECT * FROM old_table_name');
    // Add addtional column if you watch
    if (!Schema::hasColumn('old_table_name', 'deleted_at')) {
        Schema::table('new_table_name ', function (Blueprint $table) {
            $table->softDeletes();
        });
    }
}
Chaumont answered 13/12, 2022 at 6:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.