22

I want to share a variable of my views with:

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        \Schema::defaultStringLength(191);
        $customers = Customer::get();
        \View::share('customers', $customers);
    }
}

it works as expected, but when I want to migrate my tables via artisan it throws an error, that the table for customers was not found because it is checked BEFORE the migration starts. So I need something like

if(!artisan_request) {
    //request to laravel is via web and not artisan
} 

But I haven't found anything in the documentation.

2 Answers 2

46

You can check if you are running in the console by using

app()->runningInConsole()

Underneath that, all it does is check the interface type

return php_sapi_name() == 'cli' || php_sapi_name() == 'phpdbg'

You can find more on the PHP Docs site

2
  • No need to use app() instance, second one is preferable.
    – Buraco
    Aug 2, 2019 at 9:47
  • 4
    @Buraco not at all. First one is preferred. I was simply showing what goes on underneath the method.
    – Ian
    Aug 3, 2019 at 15:14
11

To detect whether the app is running in console, you can do something like this:

use Illuminate\Support\Facades\App;

if(App::runningInConsole())
{
  // app is running in console
}

See, illuminate/Foundation/Application.php:520

2
  • it's not static
    – drakonli
    Sep 1, 2020 at 6:26
  • @drakonli The App facade allows for that.
    – Mozammil
    Sep 2, 2020 at 12:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.