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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…