Tutorial

[Laravel tips] How to temporarily change a laravel environment variable without updating the .env file

Imagine the following scenario: you are working on a laravel application that dispatches some jobs to a queue. You notice in your log file that a specific job is throwing an exception, but you can’t debug it directly (with dd() for instance), since the job is consumed by a worker elsewhere.

One way to debug this issue would be to change the QUEUE_DRIVER environment variable in your .env file to sync, debug, and then revert back the change after you finish.

Or imagine that you have a test database and you need to run the migrations on it first, and you’d need to update the .env file to use the test database first, run the migrations and then revert back the change.

As you can see, in both cases, all what we need to do is to update the environment variable temporarily. And usually, it takes some time to update the .env file (you might even need to clear the configuration or restart some workers).

Luckily, it is possible to pass an environment variable to linux commands, and these variables will only be used for the current execution.

In the previous example, all what we have to do is to execute the command as follows:

QUEUE_DRIVER=sync php artisan my-artisan-command-here

You can test it yourself with tinker.

You can even pass multiple environment variables like this:

QUEUE_DRIVER=sync DB_DATABASE=testing php artisan my-artisan-command-here

As you can see, this is not a laravel specific trick, and you can use it whenever you find yourself in a situation where you need to change an environment variable temporarily.

I hope you’ll find this useful.

%d bloggers like this: