How to create a mysql db with Laravel

前端 未结 6 800
盖世英雄少女心
盖世英雄少女心 2021-02-13 14:50

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 man

6条回答
  •  囚心锁ツ
    2021-02-13 15:32

    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
    ];
    

提交回复
热议问题