16

I'm using Laravel 5.2. I've setup my first migrations and I want to run them. From the video tutorial it doesn't explain how to create a mysql db. I know I can do this manually in phpmyadmin but is there a Laravel way to do it?

This will install the migrations table:

php artisan migrate:install

Is there a similar command that will create the DB?

I'm thinking the process should be:

php artisan DB:install (or similar command)

Install the migrations table:

php artisan migrate:install

Run the migrations:

php artisan migrate

and to rollback the migrations:

php artisan migrate:rollback
user1532669
  • 2,288
  • 4
  • 36
  • 72

7 Answers7

17

Nothing provided out of the box but you could make your own command that could do this for you:

php artisan make:console CreateDatabase
// Note, in 5.3 this is make:command

Then in app/Console/Commands you'll find CreateDatabase.php. Open that sucker up and let's make a few changes:

protected $name = "make:database";
// in Laravel 5.3 + it's protected $signature

Then down below in your file we need a new function:

protected function getArguments()
{
    return [
        ['name', InputArgument::REQUIRED, 'The name of the database'],
    ];
}

Then we'll make another function called fire() which will be called upon invocation of the command:

public function fire()
{
    DB::getConnection()->statement('CREATE DATABASE :schema', ['schema' => $this->argument('name')]);
} 

And now you can just do this:

php artisan make:database newdb

Now you'll get a newdb database created for you based on your connection configuration.

Edit Forgot the most important part - you need to tell app\Console\Commands\Kernel.php about your new comand, make sure to add it to the protected $commands[] array.

protected $commands = [
    ///...,
    App\Console\Commands\CreateDatabase::class
];
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
  • And what do you include via `use` for `DB`? – atomkirk Sep 23 '16 at 17:55
  • @atomkirk It should be the Facade. `Illuminate\Support\Facades\DB` – Ohgodwhy Sep 23 '16 at 22:34
  • @ArieCwHat You're right. Although it's still possible. I'm on mobile now but I'll try to get an updated answer for this tonight. – Ohgodwhy May 31 '17 at 01:57
  • @Ohgodwhy It would be cool, but I started a thread in the Laravel's [github](https://github.com/laravel/framework/issues/19412) It would also be great if you gave your solution there :P – – UselesssCat May 31 '17 at 02:51
  • @ArieCwHat Your situation is different, as you **must** have a database setup prior to being able to create other databases, that was true at the time of my answer as well. – Ohgodwhy May 31 '17 at 03:31
  • 1
    @Ohgodwhy Then there is no way to create a database with an empty mysql server? I was trying to create the database that is used in the configuration file "database.php" (or .env file) with a command like your answer. – UselesssCat May 31 '17 at 03:41
  • @ArieCwHat Not with the database factory. Like submitted in that gist, you can do it, but only with a raw PDO connection. All queries get the connection first, before anything else. The underlying connection always has a database, unfortunately. – Ohgodwhy May 31 '17 at 04:41
  • Needed to change the signature aswell: protected $signature = 'make:database'; – Sidonai Sep 10 '20 at 23:26
  • @Sidonai Whew, this was an old one. Added that instruction as well. – Ohgodwhy Sep 11 '20 at 01:10
7

This answer might be useful if you are using different mysql connection also. I am writing code in laravel 5.5

Step:1 Create command

php artisan make:command CreateDatabaseCommand

Step:2 In app/Console/Kernel.php register the command

protected $commands = [
    CreateDatabaseCommand::class
];

Step:3 Write logic in your CreateDatabaseCommand.php file

    protected $signature = 'make:database {dbname} {connection?}';

    public function handle()
    {
     try{
         $dbname = $this->argument('dbname');
         $connection = $this->hasArgument('connection') && $this->argument('connection') ? $this->argument('connection'): DB::connection()->getPDO()->getAttribute(PDO::ATTR_DRIVER_NAME);

         $hasDb = DB::connection($connection)->select("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = "."'".$dbname."'");

         if(empty($hasDb)) {
             DB::connection($connection)->select('CREATE DATABASE '. $dbname);
             $this->info("Database '$dbname' created for '$connection' connection");
         }
         else {
             $this->info("Database $dbname already exists for $connection connection");
         }
     }
     catch (\Exception $e){
         $this->error($e->getMessage());
     }
   }

That's all. Now run your command

php artisan make:database {your-database-name} {your-connection-name}:

Note :: You should use second argument only if you want to create database in any different connection from default mysql connection otherwise command will automatically take the default db connection

Hope this will help someone :)

Vikash
  • 3,391
  • 2
  • 23
  • 39
4

If you're not going to use a Vagrant box or virtual machine for local development then you're going to have to install your database driver of choice and then create a new database.

To do that with MySQL from the command line run:

$ mysql -uroot -p
mysql> create database yourDatabaseName;

Then cp .env.example .env and update your database creds.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=yourDatabaseName
DB_USERNAME=root
DB_PASSWORD=root 

You'll have set up the username and password to your database when you first installed the driver. After this you may have to php artisan key:generate and/or 'php artisan config:clearbutphp artisan migrate` should work. Below are some tutorial resources you may find helpful:

Initial database creation and seeding with Laravel 5

How to install MySQL on OSX

Connor Leech
  • 18,052
  • 30
  • 105
  • 150
1

Vikash's response worked. (in Laravel 5.8)

Based on the response of Vikash: How to create a mysql db with Laravel

I have created the following command which creates a MySQL database with the collation that you assign. I have uploaded it to this GitHub repository

I hope it helps other developers.

Mateus Junges
  • 2,559
  • 1
  • 12
  • 24
0

You should create the DB, and set the connection parameters to it. Then, Laravel will access the DB and will run the migrations (make the tables) and the seeders.

You can found the parameters for php artisan migrate here: https://laravel.com/docs/5.2/migrations#running-migrations

Jeremias Araujo
  • 179
  • 3
  • 11
0

You can create the database using Laravel Tinker. First configure the right DB_ settings in your .env file.

Then run the following commands:

php artisan tinker

    $pdo = new PDO('mysql:host=' . env('DB_HOST'), env('DB_USERNAME'), env('DB_PASSWORD')));
    $pdo->exec('CREATE DATABASE ' . env('DB_DATABASE'));

exit

As a one liner it looks like this:

php artisan tinker --execute="(new PDO('mysql:host=' . env('DB_HOST'), env('DB_USERNAME'), env('DB_PASSWORD')))->exec('CREATE DATABASE ' . env('DB_DATABASE'))"
Roland Starke
  • 1,658
  • 1
  • 14
  • 19
-1

you have to make your modal first and make its migration table also in order to make a database. you should use: php artisan make:model -m command to make model and migration table. after that open your migration table in any texteditor to add the columns in your database table and then, use this command to migrate:

php artisan migrate

Vivek Titwal
  • 93
  • 11