Detect if running from the command line in Laravel 5

后端 未结 4 457
感情败类
感情败类 2021-02-03 22:16

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条回答
  • 2021-02-03 22:53

    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
    }
    
    0 讨论(0)
  • 2021-02-03 23:06

    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)

    0 讨论(0)
  • 2021-02-03 23:09

    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.

    0 讨论(0)
  • 2021-02-03 23:15

    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.
    }
    
    0 讨论(0)
提交回复
热议问题