How to create database schema (table) in Laravel?

后端 未结 5 1154
眼角桃花
眼角桃花 2021-02-09 07:53

I\'m new to Laravel.I\'m trying to create database in Laravel. I tried in console with:

Schema::create

5条回答
  •  情歌与酒
    2021-02-09 08:09

    my working example:

    create new artisan command:

    php artisan make:command mysql
    

    the content of App\Console\Commands\mysql.php :

    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    use Illuminate\Support\Facades\DB;
    
    class mysql extends Command
    {
        /**
         * The name and signature of the console command.
         *
         * @var string
         */
        protected $signature = 'mysql:createdb {name?}';
    
        /**
         * The console command description.
         *
         * @var string
         */
        protected $description = 'Create a new mysql database schema based on the database config file';
    
        /**
         * Create a new command instance.
         *
         * @return void
         */
        public function __construct()
        {
            parent::__construct();
        }
    
        /**
         * Execute the console command.
         *
         * @return mixed
         */
        public function handle()
        {
            $schemaName = $this->argument('name') ?: config("database.connections.mysql.database");
            $charset = config("database.connections.mysql.charset",'utf8mb4');
            $collation = config("database.connections.mysql.collation",'utf8mb4_unicode_ci');
    
            config(["database.connections.mysql.database" => null]);
    
            $query = "CREATE DATABASE IF NOT EXISTS $schemaName CHARACTER SET $charset COLLATE $collation;";
    
            DB::statement($query);
    
            config(["database.connections.mysql.database" => $schemaName]);
    
        }
    }
    

    then run: (schema_name is optionally)

    php artisan mysql:createdb schema_name
    

提交回复
热议问题