Created
March 2, 2022 06:58
-
-
Save takshaktiwari/b471717461eef699543bf9b294ae3aec to your computer and use it in GitHub Desktop.
Create database comand - Laravael
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Console\Commands; | |
use Illuminate\Console\Command; | |
use Illuminate\Support\Facades\DB; | |
use PDO; | |
class DatabaseCreateCommand extends Command | |
{ | |
/** | |
* The name and signature of the console command. | |
* | |
* @var string | |
*/ | |
protected $signature = 'database:create {dbname} {--connection=} {--collation=utf8mb4_unicode_ci}'; | |
/** | |
* The console command description. | |
* | |
* @var string | |
*/ | |
protected $description = 'Create Database with command'; | |
/** | |
* Create a new command instance. | |
* | |
* @return void | |
*/ | |
public function __construct() | |
{ | |
parent::__construct(); | |
} | |
/** | |
* Execute the console command. | |
* | |
* @return int | |
*/ | |
public function handle() | |
{ | |
$connection = $this->hasArgument('connection') && $this->argument('connection') ? $this->argument('connection') : DB::connection()->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME); | |
$collation = $this->option('collation'); | |
$hasDB = DB::connection($connection)->select("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = "."'".$this->argument('dbname')."'"); | |
if($hasDB){ | |
$this->error($this->argument('dbname').': database is already exists'); | |
exit; | |
} | |
DB::connection($connection)->select('CREATE DATABASE '. $this->argument('dbname').' COLLATE '.$collation); | |
$this->info("Database `".$this->argument('dbname')."` created for connection '$connection' with collation '$collation' has been created ! "); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment