Check if a Laravel request is from the CLI
Published on by Eric L. Barnes
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:
if (config('settings.profile')) { \DB::connection()->enableQueryLog();}
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.
app()->runningInConsole()
With this I could just an inverse check to make sure my code only runs when it's a web request:
if (config('settings.profile') && ! app()->runningInConsole()) { \DB::connection()->enableQueryLog();}
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.
Eric is the creator of Laravel News and has been covering Laravel since 2012.