5

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.

1
  • I don't see anything built-in. You could probably PHP's debug_backtrace to detect that a migration file is currently in use. Commented Mar 14, 2019 at 17:30

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

I'd note that if you use Artisan commands for anything else - including Laravel's built-in cron - this would apply there too.
@Peter not really sufficient... I don't want it to trigger at every artisan command... Just the migrate ones. Is there a way to get the currently running command?
I've added an update that might get your the info you need in an ugly but functional way.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.