How to create a mysql db with Laravel

前端 未结 6 803
盖世英雄少女心
盖世英雄少女心 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:31

    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 :)

提交回复
热议问题