How to create new empty database with Laravel over Model

前端 未结 5 1620
清酒与你
清酒与你 2021-01-25 20:55

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

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-25 21:22

    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

提交回复
热议问题