Using an Artisan command to create a database in Laravel or Lumen

We’re heavy users of Laravel and Lumen here at EvaluAgent, and we needed a way to automatically create the database for each of our services when we deployed them. A quick Google search provides mixed results, so I thought I’d blog our solution in an effort to help others.

We found that when using the built in DB functionality in Laravel/Lumen it attempted to connect to the non-existing database resulting in an exception being thrown, so we decided to use the env to configure a native PDO connection to create database.

There may be a way to get the PDO connection directly from the DB Facade but, to be honest, time was short and we just needed to get on.

First we created a Artisan Command named DatabaseCreateCommand and then registered it, the source for this is below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use PDO;
use PDOException;

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 fire()
    {
        $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,
                env('DB_CHARSET'),
                env('DB_COLLATION')
            ));

            $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);
    }
}

Once we’ve deployed our services we can now just run the following commands to create the configured database and run the related migrations.

1
2
php /var/www/artisan db:create
php /var/www/artisan migrate

I hope this helps.

This post was tagged with:
← Back