How to set an env variable within a Composer script

And why you might want to do it

Joel Clermont
Joel Clermont

I love using Composer scripts to automate things and as a form of self-documentation.

On a recent project, I needed to call a Composer script from another Composer script, but with one specific environment value changed. It's a long story, but I wanted to call a fairly complicated migration/seeder combo but with a different database host. This is not something I'd typically do, but it solved an immediate problem as we were improving the project.

So how can you do this? With the Composer script alias, I can't just prefix the command like this DB_HOST=new-value @composer original-script. That will fail because Composer only resolves those aliases at the beginning of a script.

But Composer provides an alternate way to do this:

    "scripts": {
        "original-script": [
            "@php long-artisan-command",
            "@php another-long-command"
        "new-script": [
            "@putenv DB_HOST=new-value",
            "@composer original-script"

So in my new-script, by calling @putenv I am adding an environment variable which will be present when original-script runs.

Now, I can keep things simple and not duplicate a bunch of logic just to tweak one environment variable!

Here to help,


P.S. Speaking of joining new projects, let me know if you'd like some help on your project. We're particularly good at solving pain points that you may have just become numb to over time.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.