Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mikromike's avatar

laravel 9 how to create new database by DB:raw

Hello

Laravel 9.19, Mysql 5.7.33, Env: windows 10.

I tried to create database for multitenat environment. I have already looking fr hour solution for this.

this is best what I have found:

   $created_databse = DB::statement(DB::raw('CREATE DATABASE IF NOT EXISTS '. $schemaName));

Process is following:

  1. purge exist connection:

     DB::purge('landlord');
    
  2. reconnect serverl level as there is no databse connection availabel as I am creating it.

    $conn = DB::reconnect('mysqlserver');
    
  3. create new database

    $schemaName = $tenant->databse;
    $created_databse = DB::statement(DB::raw('CREATE DATABASE IF NOT EXISTS '. $schemaName));
    
  4. Looks like I can talk with mysql server as error is:

"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax.

--> what is the correct way to do it with laravel 9?

Thanks Mika.

0 likes
7 replies
mikromike's avatar

changed line to :

   DB::raw('CREATE DATABASE IF NOT EXISTS '.$schemaName);

checked in mysqlworkbench sql : CREATE DATABASE IF NOT EXISTS Foo; and CLI.

both works.

still not in DB::raw();

Tray2's avatar

You really should use a single database for this, it will save you tons of headaches in the long run.

mikromike's avatar

@Tray2, thansk, I have used three diffrent databses al the time.

Problem was syntax.

now works.

mikromike's avatar
mikromike
OP
Best Answer
Level 27
     public function createDatabase()
    {

      $tenants = $this->get();

    foreach ($tenants as $tenant) {
        $schemaName = $tenant->database;

    try{
         DB::purge('landlord');
        $conn = DB::reconnect('mysqlserver');

       if(!$conn ) {
           return false;
         }

      $create_database = DB::raw('CREATE DATABASE IF NOT EXISTS ' .$schemaName);
       DB::statement($create_database);

    //   $tables = DB::select("SELECT table_name FROM information_schema.tables WHERE 
    //  table_schema = '{$new_db_name}'");
  } // end of try block 
   catch(\Exception $e){       
       return false;
    }
    } // end of foreach 
   }

Finally, works.

Please or to participate in this conversation.