Skip to content

Instantly share code, notes, and snippets.

@AEROGU
Last active August 30, 2022 20:53
Show Gist options
  • Save AEROGU/11612785f6b76e53fb16b822de9c645d to your computer and use it in GitHub Desktop.
Save AEROGU/11612785f6b76e53fb16b822de9c645d to your computer and use it in GitHub Desktop.
Create Laravel db:create artisan command for MySQL.

Create Laravel db:create artisan command for MySQL.

With this command, when your .env file is configured, you can create your project database with php artisan db:create when is the first time you clone your project.

To create this command, execute: php artisan make:command dbcreate, and then , a file named dbcreate.php will be generated in ./app/Console/Commands/dbcreate.php, then just copy and paste the code of dbcreate.php file.

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* Create new database based on config file.
* 1.- Execute: php artisan make:command dbcreate
* 2.- Go to: app/Console/Commands/dbcreate.php
* 3.- Copy and paste there the content of this file.
* 4.- Now you can execute: php artisan db:create
*/
class dbcreate extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'db:create {name?}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new MySQL database based on the database config file or the provided name';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$schemaName = $this->argument('name') ?: config("database.connections.mysql.database");
$charset = config("database.connections.mysql.charset",'utf8mb4');
$collation = config("database.connections.mysql.collation",'utf8mb4_unicode_ci');
config(["database.connections.mysql.database" => null]);
$query = "CREATE DATABASE IF NOT EXISTS $schemaName CHARACTER SET $charset COLLATE $collation;";
DB::statement($query);
config(["database.connections.mysql.database" => $schemaName]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment