How to get currently used Artisan console command name in Laravel 5?

Viewed 3611

Problem / What I've tried:

Getting the currently used controller and action in Laravel 5 is easy (but not as easy as it should be), however I'm stuck with getting the currently used artisan console command.

To fetch the controller name I do this:

$route = Route::getRoutes()->match(Request::capture());
$listAction = explode('\\', $route->getActionName());
$rawAction = end($listAction);
// controller name and action in a simple array
$controllerAndAction = explode('@', $rawAction);

But when calling from a console action, it always returns the default index controller's name ("IndexController" or so in Laravel). Does anybody know how to make this ?

By the way I've also worked throught Request::capture() but this still gives no info about the command.

3 Answers

The simplest way is to just to look at the arguments specified on the command line:

if (array_get(request()->server(), 'argv.1') === 'cache:clear') {
    // do things
}

Yes, you can use $_SERVER directly, but I like to use the helper functions or the Facades, as those will give you the current data. I go from the assumption that - during unit tests - the superglobals might not always reflect the currently tested request.

By the way: Obviously can also do array_get(request()->server('argv'), '1') or something alike. (request()->server('argv.1') doesnt work at this point). Or use \Request::server(). Depends on what you like most.

Related