How to request a database password when starting a Laravel 5 migration

Laravel transitions must be performed with a particularly high privilege level because they perform DDL operations. I would like to start migrations as a named user without saving the password anywhere. This will require a password for the user when starting the migration from the command line. I cannot find a way to achieve this through the connection configuration.

Is there a way to achieve this through a connection configuration?

If not, is there a way to migrate with a thin layer of custom code on top to establish a database connection in the usual way? for example, write a script / artisan command that asks if it connects to the database and then transfers the existing migration code to Laravel?

+4
source share
2 answers

If you just need to ask the user for credentials to maintain the database to perform the migration, this can be easily achieved by wrapping the command artisan migratein another command requesting the appropriate credentials. Therefore, it is enough to follow these steps:

1. Create a new command:

artisan make:console MigratePrivilegedCommand --command="migrate:privileged"

2. Add the necessary code to process user input and perform the migrations in the new class of commands:

class MigratePrivilegedCommand extends Command
{
    protected $signature = 'migrate:privileged';
    protected $description = 'Run migrations as a priviledged database user.';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        // Set the username and password for the
        // database connection from user input
        config([
            'database.connections.mysql.username' => $this->ask('What is your username?'),
            'database.connections.mysql.password' => $this->secret('What is your password?')
        ]);

        // Call the migrate command and you're done    
        $this->call('migrate');
    }
}

3. Register a new command in App\Console\Kernel.php:

protected $commands = [
    ...
    \App\Console\Commands\MigratePrivilegedCommand::class,
];

And now you can start the migration, which requires privileged database credentials:

php artisan migrate:privileged
+4
source

CLI .

database.php

'connection_without_password' => [
            'driver'    => 'mysql',
            'host'      => 'hostname,
            'database'  => 'database',
            'username'  => '$username',
            'password'  => '$password',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],

.

Schema::connection('connection_without_password')->create('users', function ($table) {
    $table->increments('id');
});
0

All Articles