Check if a Laravel request is from the CLI

Tutorials

April 28th, 2021

runningInConsole.png

There might be times where you need to know if a request to your Laravel app is coming from the CLI or from the web. As an example, I wanted to turn on the query log to dump out all the SQL queries.

In AppServiceProvider I added a simple config check to turn on the the log:

1if (config('settings.profile')) {
2 \DB::connection()->enableQueryLog();
3}

With this in place, it would run for web requests, as I wanted, but the side effect is it would also be turned on in our queue jobs and other CLI tasks.

Laravel runningInConsole

Laravel provides a simple helper called runningInConsole that you can use to help determine what environment you are in.

1app()->runningInConsole()

With this I could just an inverse check to make sure my code only runs when it's a web request:

1if (config('settings.profile') && ! app()->runningInConsole()) {
2 \DB::connection()->enableQueryLog();
3}

If you ever come to a situation where you need to know where your app is running, keep this in mind. It's an excellent way of utilizing the internal Laravel helpers to keep your code clean and easy to read.

Filed in:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.