Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 648
Sliq Avatar asked Mar 07 '16 10:03

Sliq


People also ask

What is Laravel artisan command?

Artisan is the name of the command-line interface included with Laravel. It provides a number of helpful commands for your use while developing your application. It is driven by the powerful Symfony Console component.

How do I use Console commands in Laravel?

Simply add a new command like $schedule->command('command:name')->hourly(); inside schedule function.


2 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.

like image 85
Blizz Avatar answered Sep 21 '22 18:09

Blizz


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).

like image 25
dmmd Avatar answered Sep 21 '22 18:09

dmmd