Skip to content

Instantly share code, notes, and snippets.

@takshaktiwari
Created March 2, 2022 06:58
Show Gist options
  • Save takshaktiwari/b471717461eef699543bf9b294ae3aec to your computer and use it in GitHub Desktop.
Save takshaktiwari/b471717461eef699543bf9b294ae3aec to your computer and use it in GitHub Desktop.
Create database comand - Laravael
<?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