Last active
December 21, 2019 08:16
-
-
Save milosb793/68575e39a6654be59efeb64a6be34317 to your computer and use it in GitHub Desktop.
Laravel Command used for creating database.
This file contains 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 PDO; | |
use PDOException; | |
use Illuminate\Console\Command; | |
class DatabaseCreateCommand extends Command | |
{ | |
/** | |
* The console command name. | |
* | |
* @var string | |
*/ | |
protected $name = 'db:create'; | |
/** | |
* The console command description. | |
* | |
* @var string | |
*/ | |
protected $description = 'This command creates a new database'; | |
/** | |
* The console command signature. | |
* | |
* @var string | |
*/ | |
protected $signature = 'db:create'; | |
/** | |
* Execute the console command. | |
*/ | |
public function handle() | |
{ | |
$database = env('DB_DATABASE', false); | |
if (! $database) { | |
$this->info('Skipping creation of database as env(DB_DATABASE) is empty'); | |
return; | |
} | |
try { | |
$pdo = $this->getPDOConnection(env('DB_HOST'), env('DB_PORT'), env('DB_USERNAME'), env('DB_PASSWORD')); | |
$pdo->exec( | |
sprintf( | |
'CREATE DATABASE IF NOT EXISTS %s CHARACTER SET %s COLLATE %s;', | |
$database, | |
config('database.connections.mysql.charset'), | |
config('database.connections.mysql.collation') | |
) | |
) or die(print_r($pdo->errorInfo(), true)); | |
$this->info(sprintf('Successfully created %s database', $database)); | |
} catch (PDOException $exception) { | |
$this->error(sprintf('Failed to create %s database, %s', $database, $exception->getMessage())); | |
} | |
} | |
/** | |
* @param string $host | |
* @param integer $port | |
* @param string $username | |
* @param string $password | |
* @return PDO | |
*/ | |
private function getPDOConnection($host, $port, $username, $password) | |
{ | |
return new PDO(sprintf('mysql:host=%s;port=%d;', $host, $port), $username, $password); | |
} | |
} |
Additionally, a command could be ran automatically with composer, for example, on composer install
post-install
event:
"post-install-cmd": [
"@php artisan ui bootstrap --auth",
"@php artisan db:create"
],
Other events: https://getcomposer.org/doc/articles/scripts.md#command-events
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Place file at
app/Console/Commands/
inside of your project.