9

how to create a TEMPORARY table in laravel, insert a record and retrieve hello, I'm trying to create a temp table in laravel and insert a record and retrieve that record from temp table and then drop the table.

But my temp table is not created

DB::raw(“CREATE TEMPORARY TABLE tbl_temp(temp_id VARCHAR(100),tempcolumn1 VARCHAR(100),tempcolumn2 VARCHAR(100),tempcolumn3 VARCHAR(100)) ;
Kirill
  • 105
  • 2
  • 8
Abbas Ahmad
  • 377
  • 3
  • 4
  • 13

4 Answers4

14

Try this

// CREATE TEMPORARY TABLE

$productList = DB::insert( DB::raw( "CREATE TEMPORARY TABLE tempproducts") );

// DELETE TEMPORARY TABLE

$dropTable = DB::unprepared( DB::raw( "DROP TEMPORARY TABLE tempproducts" ) );
Manish
  • 3,443
  • 1
  • 21
  • 24
1

I have recently created a temp table( laravel 8) as such:

public function createLocalStoreProductTable(): \Illuminate\Http\JsonResponse
    {
        $tempTable = env("DB_TEMP_STORE_PRODUCT_TABLE_NAME");
        DB::connection('mysql')->statement(
            "CREATE TABLE " . $tempTable . " (
                    `uid` int(10) unsigned NOT NULL AUTO_INCREMENT,
                    `store_uid` int(10) unsigned NOT NULL)
                     PRIMARY KEY (`uid`),
                     KEY `store_uid` (`store_uid`)
                     ) ENGINE=InnoDB AUTO_INCREMENT=3035849 DEFAULT 
                       CHARSET=utf8;"

 return response()->json(array('success' => true), Response::HTTP_OK);

1

If you want a temporary table containing the result of a query:

DB::statement('CREATE TEMPORARY TABLE your_table_name SELECT ...insert query here');

If you want to define the table before inserting rows:

DB::statement('CREATE TEMPORARY TABLE your_table_name (...insert normal DDL here)');

Then just insert rows as in a normal table:

DB::table('your_table_name')->insert(["column" => "value"]);

or get result as in normal table:

DB::table('your_table_name')->get();
Santosh Dangare
  • 685
  • 1
  • 4
  • 15
-6

With Schema you can create temp tables...

 Schema::create('temp', function (Blueprint $table) {
                $table->increments('id');
                $table->string('session_id');

            });
Abbas Ahmad
  • 377
  • 3
  • 4
  • 13