42

I have a use case where we need to modify application flow if the application is being run from the command line via Artisan (migrations, seeds, route:list).

In Laravel 4 this could be done like this:

App::runningInConsole()

Is there an equivalent in Laravel 5?

Using the Environment (.env) variables isn't preferred in this case as these commands occasionally need to be run on production (pointing to production resources) and I'd prefer to avoid resorting to duplicate (.env.commandline) files.

Forrest Marvez
  • 895
  • 1
  • 8
  • 16

4 Answers4

45

Not sure about any prior versions but in Laravel 5.2 you can still do App::runningInConsole() although it's not mentioned in the documentation.

Fahmi
  • 2,607
  • 1
  • 20
  • 15
29

You can use the PHP function php_sapi_name (http://php.net/manual/en/function.php-sapi-name.php), to found out if the script was launched from a command or not.

In your case, you should check something like

if (strpos(php_sapi_name(), 'cli') !== false) {
    // Run from command
}

You may have to check the doc to find the proper value to check in each case though. (It may differ sometimes, but basically there should always be a different output from a script launched through a command)

Clément Malet
  • 5,062
  • 3
  • 29
  • 48
  • This works, was hoping for a built in solution as before but further research yields that functionality has been deprecated. Marking as the solution. – Forrest Marvez Mar 18 '15 at 19:21
  • @ForrestMarvez I'm not 100% sure, but I think it has been marked as deprecated on Laravel 5 because the result of the function wasn't always the same on each server / config. – Clément Malet Mar 18 '15 at 19:23
21

As of Laravel 5.1 this works... $app->runningInConsole() https://laravel.com/api/5.1/Illuminate/Foundation/Application.html

Basic usage:

if (! $app->runningInConsole()) {
 // do something
}
BrianCP
  • 311
  • 2
  • 4
17

Anyone can use laravel app() helper function to avoid any namespace related issue. So to check if script is running in cli or browser, can be using this line of code app()->runningInConsole()

Basic usage:

if ( app()->runningInConsole() ){
    // it's console.
}
Tamim
  • 916
  • 11
  • 19