Last active
September 17, 2015 14:09
-
-
Save TimTruston/c98f9aa2a972136a1295 to your computer and use it in GitHub Desktop.
Artisan command for quickly creating a database.
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; | |
| class DBCreate extends Command | |
| { | |
| /** | |
| * The name and signature of the console command. | |
| * | |
| * @var string | |
| */ | |
| protected $signature = 'db:create'; | |
| /** | |
| * The console command description. | |
| * | |
| * @var string | |
| */ | |
| protected $description = 'Creating the database.'; | |
| /** | |
| * Create a new command instance. | |
| * | |
| * @return void | |
| */ | |
| public function __construct() | |
| { | |
| parent::__construct(); | |
| } | |
| /** | |
| * Execute the console command. | |
| * | |
| * @return mixed | |
| */ | |
| public function handle() | |
| { | |
| $this->comment(''); | |
| $this->comment('====================================='); | |
| $this->comment(''); | |
| // Fetch the defined database name | |
| $db_type = \Config::get('database.default'); | |
| $connection = \Config::get('database.connections.'.$db_type); | |
| $host = $connection['host']; | |
| $username = $connection['username']; | |
| $password = $connection['password']; | |
| $database = $connection['database']; | |
| // Get db name | |
| $db = $this->ask('What is the name of the database you want to create?', $database); | |
| $this->comment(''); | |
| $this->comment('-------------------------------------'); | |
| $this->comment(''); | |
| // Try to create it | |
| try | |
| { | |
| // Create connection | |
| $conn = new \mysqli($host, $username, $password); | |
| $this->info(json_encode($conn)); | |
| // return $conn; | |
| // Check connection | |
| if ($conn->connect_error) { | |
| die("Connection failed: " . $conn->connect_error); | |
| } | |
| // Create database | |
| $sql = "CREATE DATABASE `$db`"; | |
| if ($conn->query($sql) === TRUE) { | |
| echo "Sucessfully created database $db!"; | |
| } else { | |
| echo "Error creating database: " . $conn->error; | |
| } | |
| $conn->close(); | |
| } | |
| catch(Exception $e){ | |
| $this->info('There was a problem creating database "'.$db.'"'); | |
| $this->info(json_encode($e)); | |
| die; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment