I want to create a database using a command. I am using postgresql. I am creating the tables using the migrations but before that I want to create the database and several schemas. I am using this command:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class pgsql extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'pgsql:createdb {name?}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new pgsql database schema based on the database config file';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$dbname = env('DB_DATABASE');
$dbuser = env('DB_USERNAME');
$dbpass = env('DB_PASSWORD');
$dbhost = env('DB_HOST');
try {
$db = new \PDO("pgsql:host=$dbhost", $dbuser, $dbpass);
$test = $db->exec("CREATE DATABASE \"$dbname\" WITH TEMPLATE = template0 encoding = 'UTF8' lc_collate='Spanish_Spain.1252' lc_ctype='Spanish_Spain.1252';");
if($test === false)
throw new \Exception($db->errorInfo()[2]);
$this->info(sprintf('Successfully created %s database', $dbname));
}
catch (\Exception $exception) {
$this->error(sprintf('Failed to create %s database: %s', $dbname, $exception->getMessage()));
}
}
}
But I get this error:
Failed to create database: SQLSTATE[08006] [7] could not translate host name "connect_timeout=30" to address: Unknown server error
Like I said I want to create a new database in Laravel, I am using this way but is not working, if there is other way to do it I would like to know.
EDIT1: It works fine now, I just pick the values from the config like you said @Dimitri Mostrey :
$dbname = config('database.connections.pgsql.database');
$dbuser = config('database.connections.pgsql.username');
$dbpass = config('database.connections.pgsql.password');
$dbhost = config('database.connections.pgsql.host');