Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current console command in Laravel

I can see if a script is running in the console with the App::runningInConsole() command, but I would like to know (for audit logging purposes) which command has been run from console.

To add some context - I need to log whenever a system or user accesses a certain type of data. For users, that's pretty simple - I can use Auth::user() and get their IP address from Request, but for console commands, it's a little more difficult.

I can figure out if a console command is running, which is good, but I need to be able to record which console command is running.

like image 488
samlev Avatar asked Aug 13 '15 16:08

samlev


2 Answers

I do not see a way to get that information directly Laravel. I'm also not sure how that would be possible, as you can have one command executing other commands or even creating a new application instance like some test tools do.

There is however a way to achieve that using plain PHP. You can check the server/environment variables to identify how application was executed.

Have a look at

dd($_SERVER['argv']);

If you run a command this should give you the command name in $_SERVER['argv'][1]

You can find more information here: http://php.net/manual/en/reserved.variables.argv.php

like image 176
jedrzej.kurylo Avatar answered Sep 19 '22 15:09

jedrzej.kurylo


To get console command together with arguments you should use something like that:

$command = \Request::server('argv', null);
if (is_array($command)) {
   $command = implode(' ', $command);
}

In Laravel you can use \Request:server to get $_SERVER variables.

like image 44
Marcin Nabiałek Avatar answered Sep 16 '22 15:09

Marcin Nabiałek