Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

is there any way to create new database with Laravel CodeBehind ? I mean, I'm not able to use php artisan or something like that. Just because I want to create a database for every registered user. After that I can use migration. I'm using Laravel 5.2. Thanks for your support already.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
615 views
Welcome To Ask or Share your Answers For Others

1 Answer

for this, you can create an Artisan Command

Step:1 Create command

php artisan make:command CreateDatabaseCommand

Step:2 In app/Console/Kernel.php register the command

protected $commands = [
    CreateDatabaseCommand::class
];

Step:3 Write logic in your CreateDatabaseCommand.php file

protected $signature = 'make:database {dbname} {connection?}';

    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());
     }
   }

Now your ready Artisan command call like this way

php artisan make:database {database-name} {connection-name}

See my sample

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...