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

bobdebower's avatar

Create automatically a database after user rigister.

After a user register. i want to create automatically a new database, with some kind of a script. So i need to write some kind of a script that creates automatically a db_name and also recognizes the user with the db_name

I'am currently saving db_name in my user database/migration.

 public function up()
    {
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('db_name')->nullable();
        $table->timestamps();
      });

i'am using middleware to connect to a database dynamic(db_name) works good!

 public function handle(Request $request, Closure $next)
   {
      $user = $request->user();

    Config::set('database.connections.mysql.database', $user->db_name);

    DB::purge('mysql');

    DB::reconnect('mysql');

    return $next($request);
    }

}

and now i need to find a way to do this automatically creat the db_name automatically. also some kind of way to check if to user already had a db_name. maybe with laravel job? help me please ;)

0 likes
13 replies
automica's avatar

You can’t generate new databases from within a laravel application.

Sounds a bit odd why you want to do that. If you are trying to create content for a specific customer I would suggest looking at https://tenancyforlaravel.com/

This will allow you to build a app where all models have an additional tenant_id and filter content so tenants can only see and interact with their data, whilst sharing a common database structure.

3 likes
bobdebower's avatar

I want to create a database for every client. and acces the database for every user with a usertoken

Well, i know it's possible to create a command to create a database with a artisan command. like this.

 public function handle()
     {
    try {
        $dbname = $this->argument('dbname');
        $connection = $this->hasArgument('connection') && $this->argument('connection') ? $this->argument('connection') : DB::connection()->getPDO()->getAttribute(PDO::ATTR_DRIVER_NAME);

        $hasDb = DB::connection($connection)->select("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = " . "'" . $dbname . "'");

        if (empty($hasDb)) {
            DB::connection($connection)->select('CREATE DATABASE ' . $dbname);
            $this->info("Database '$dbname' created for '$connection' connection");
        } else {
            $this->info("Database $dbname already exists for $connection connection");
        }
    } catch (\Exception $e) {
        $this->error($e->getMessage());
    }
}

but i want to be able to automatically do this for each user and store it in the db_name in my user table. any suggestions?

Thank you for your respond

bugsysha's avatar

In app/Providers/EventServiceProvider.php:18 there is an Illuminate\Auth\Events\Registered event that you can listen to. Just append another listener that will do what you want. I suggest that you push the execution of that listener to the queue.

1 like
Snapey's avatar

Look at the code in the existing migrations. Its just a class you can instigate (Blueprint) and then run the methods for the various column types and names.

You can put the same code as a migration in any other class.

1 like
bobdebower's avatar

Hey guy's the big issue i'am trying to solve is to be able to create a database for very client after a user register. i want to create a database for every client. thats why i'am using middleware to create dynamic dtabase. like my code above. But i want to be able to do this all automatically

Snapey's avatar
Snapey
Best Answer
Level 122
$database = 'user_5';
DB::statement("CREATE DATABASE IF NOT EXISTS $database CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");

and then run migrations as explained.

See also https://youtu.be/592EgykFOz4

make sure you don't use any user input in the DB statement

martinbean's avatar

@bobdebower Why? So if 10,000 users register on your app you want to create 10,000 databases…?

2 likes
bugsysha's avatar

@bobdebower just imagine if Laracasts had a database for every user. Or even Facebook or Google... What a nightmare that would be.

1 like
automica's avatar

Indeed. Especially as the app itself will also need a DB to manage Authentication and guest users.

Sounds like the architecture of this application needs more thought

2 likes
Snapey's avatar

You can’t generate new databases from within a laravel application.

best answer?

I showed how to programatically create a database.

Please or to participate in this conversation.