Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: detect if running migrations

I have setup some event listeners in which I would like to detect if I'm runnnig database migrations or a normal request/command.

Is there some way of knowing this? Global flag? Environment?

Thanks in advance.

like image 704
Gonçalo Marrafa Avatar asked Jan 26 '23 14:01

Gonçalo Marrafa


2 Answers

You can check if the console is being used with App::runningInConsole() ... that might be sufficient depending on how you are running the migrations.

Update:

OK, after doing some more digging, it looks like you can hack your way to the info you need using the follow example:

if(app()->runningInConsole()) {
    // we are running in the console
    $argv = \Request::server('argv', null);

    // :$ php artisan migrate:refresh -v
    //
    // gives:
    //
    // $argv = array (
    //      0 => 'artisan',
    //      1 => 'migrate:refresh',
    //      2 => '-v',
    // )  

    if($argv[0] == 'artisan' && \Illuminate\Support\Str::contains($argv[1],'migrate')) {
        // we are running the artisan migrate command
    }
}

Source: How to get the current console command in Laravel

like image 142
Peter Avatar answered Mar 11 '23 14:03

Peter


Actually, Laravel fires several events while running migrations:

Illuminate\Database\Events\MigrationsStarted : A batch of migrations is about to be executed.

Illuminate\Database\Events\MigrationsEnded : A batch of migrations has finished executing.

Illuminate\Database\Events\MigrationStarted : A single migration is about to be executed.

Illuminate\Database\Events\MigrationEnded : A single migration has finished executing.

You can utilize this to do anything you want. For example:

// change default Log channel when running migrations
Event::listen(function (MigrationsStarted $event) {
    config()->set('logging.default', 'migration');
});

In your case, you can set a key in your app config files like app.running_migrations and set it to true in the event listener.

like image 33
AmirZpr Avatar answered Mar 11 '23 15:03

AmirZpr