Skip to content

Instantly share code, notes, and snippets.

@yavgel85
Last active March 26, 2021 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yavgel85/68ab99fda10d8c03833cff67a7f3d4e8 to your computer and use it in GitHub Desktop.
Save yavgel85/68ab99fda10d8c03833cff67a7f3d4e8 to your computer and use it in GitHub Desktop.
Creating the database #laravel #db #command
<?php
// After setting the environment variables, we can go ahead and create a new Database. We can utilize the power of PHP artisan here with Laravel commands.
# Step 1
// Fire up the command line and navigate to the project’s root directory Run the following command – php artisan make:command CreateMySQLDb
# Step 2
// In the code editor file explorer, locate the new command file which is named CreateMySQLDb.php within the following folder app/Console/Commands. Edit the contents to look like the following snippet and save it.
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class CreateMySQLDb extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'create:mysqlDb {name?}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new mysql 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()
{
$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]);
}
}
# Step 3
// Go back to the console and execute the following command php artisan create:mysqlDb laraveldb Now you can go check out phpMyAdmin to see the newly created database ‘laraveldb’. We are set to start making our migrations.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment