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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With