3

Is it possible to create an Artisan call or command for

php artisan migrate

like Artisan::call('migrate);

So i can migrate missing tables to my database when connection is changed dynamically.

  Config::set('database.connections.dynamicdb', array(
        'driver'    => 'mysql', 
         'host'      => '127.0.0.1',
         'database'  =>  $database_name,
         'username'  =>  'test_user',
         'password'  =>  '123456',
         'charset'   => 'utf8mb4',
         'collation' => 'utf8mb4_unicode_ci',
         'strict'    => false,
         'options'   => [                                
               \PDO::ATTR_EMULATE_PREPARES => true
            ]
       ));

  Artisan::call('migrate');

Or is there a way to create a command for it? Please suggest some solution.

Lano Angel
  • 299
  • 5
  • 18
  • You answered your own question - `Artisan::call('migrate')`. Have you tried that? Are you having issues with it? – ceejayoz Feb 06 '19 at 21:11
  • It doesnt work. Mine is laravel 5.6 – Lano Angel Feb 06 '19 at 21:12
  • Define "it doesn't work". What happens? What errors or behavior do you get? – ceejayoz Feb 06 '19 at 21:13
  • Ohk i will tell you the scenario. I have used a middleware to change connection dynamically and after config is set to the users database , I run the artisan command. It doesnt show error. – Lano Angel Feb 06 '19 at 21:15
  • 1
    Does the page "hang" and just sit there? You might need to pass the `--force` if this is in production; see https://stackoverflow.com/questions/37953783/laravel-5-dynamically-run-migrations. – ceejayoz Feb 06 '19 at 21:18
  • `Artisan::call('migrate', array('--path' => 'app/migrations', '--force' => true));` I ran this command while login still doesnt work. – Lano Angel Feb 06 '19 at 21:23
  • 1
    You likely also need to tell it to do `--database dynamicdb`. You continue to say "doesn't work" without indicating what happens - whether you get an error, a never-ending loading indicator, or it just continues on as if it had succeeded. – ceejayoz Feb 06 '19 at 21:25
  • ` \Artisan::call('migrate', array('--path' => 'app/migrations', '--force' => true , '--database' => 'dynamicdb'));` I run this command. It doesnt show any error. Still not migrated. – Lano Angel Feb 06 '19 at 21:29

2 Answers2

7

Try this code:

\Artisan::call('migrate',
 array(
   '--path' => 'database/migrations',
   '--database' => 'dynamicdb',
   '--force' => true));

Because my default it takes /app as path and the migrations are placed in database/migrations. So this will work as it worked for me when creating new project.

Devender Gupta
  • 496
  • 5
  • 22
0
use Artisan;

Artisan::call('migrate', 
[
   '--path' => 'database/migrations',
   '--database' => 'dynamicdb',
   '--force' => true
]);

You can call the Artisan command from anywhere. This is worked in Laravel 10.x

Syamlal
  • 714
  • 1
  • 11
  • 20