Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

princelionelnzi's avatar

Create a database in Laravel

I have created a command line which will be used to create a new postgres database.

This is the handle method of the command class:

public function handle()
    {
        $database = env('DB_DATABASE', false);

        if (! $database) {
            $this->info('Skipping creation of database as env(DB_DATABASE) is empty');
            return;
        }

        try {
            //Connecting to postgres
            $pdo = $this->getPDOConnection(env('DB_HOST'), env('DB_USERNAME'), env('DB_PASSWORD'));

            //Creating the database with the database name provided in the .env file
            $pdo->exec(sprintf(
                'CREATE DATABASE IF NOT EXISTS %s ;', $database
            ));

            $this->info(sprintf('Successfully created %s database', $database));

        } catch (PDOException $exception) {
            $this->error(sprintf('Failed to create %s database, %s', $database, $exception->getMessage()));
        }
    }

The issue is that, I always receive a success message telling me that the database has been create but in reality the database is never created. Even when I run the command 10 times, I will get 10 success message but no database created.

Kindly help me solve this problem.

0 likes
6 replies
bobbybouwmann's avatar

Have you tried to catch the output of the exec call?

$output = $pdo->exec(sprintf(
    'CREATE DATABASE IF NOT EXISTS %s ;', $database
));

$this->info($output);
princelionelnzi's avatar

This is what I get as error:

2017-04-11 12:42:43 BST ERROR:  syntax error at or near "NOT" at character 20
2017-04-11 12:42:43 BST STATEMENT:  CREATE DATABASE IF NOT EXISTS dbname CHARACTER SET  COLLATE ;
princelionelnzi's avatar
Level 1

Thanks, your answers have been really helpful to me.

Please or to participate in this conversation.