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

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

php - How to create new empty database with Laravel over Model

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...