Sliq
Sliq

Reputation: 16494

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

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.

Upvotes: 6

Views: 4862

Answers (3)

Blizz
Blizz

Reputation: 8400

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.

Upvotes: 9

dmmd
dmmd

Reputation: 3009

As per the Symfony\Component\Console\Command\Command class, the method to return the name of the command (eg. my:command) is:

$this->getName();

You should use it from within an Artisan command extending Illuminate\Console\Command (default on Artisan commands).

Remember that it will return only the command name and not the available parameters (eg. for the command signature my:command {--with-params=} it will only return my:command).

Upvotes: 4

ijpatricio
ijpatricio

Reputation: 170

Reflection might be of help? Try this:

$var = new \ReflectionClass($this);
dd($var);

Upvotes: -2

Related Questions