Oct 21, 2022

Set Environment Variables In Valet To Simplify Your .Env Files

Every time I set up a new Laravel project, I open the .env file and edit the same variable again and again. I recently realised I can set my common env variables directly in Valet, so they are automatically injected in all my projects.

One good example is the DB_PASSWORD variable. I use the root user locally, but I still set a password as a good practice. Another example is your log or mailer configuration. Usually, you have a favorite config that you use in all projects, at least in your local dev environment.

I came across this article showing how you can set env variables directly at the root of your project folder in .valet-env.php. If I understand correctly it's usefull if your project doesn't use a .env file or maybe if you have multiple domains but it's still per project. That's not what I'm looking for.

I found that Valet will also load a common file from the .config folder if no .valet-env.php exists in your project. That's what I want!

How to load env variables in Valet

With Macos, create ~/.config/valet/.valet-env.php. It must return a PHP array with your env variables.

1<?php
2 
3return [
4 '*' => [ // Applies to all env
5 'DB_PASSWORD' => 'this_is_my_password',
6 ],
7];

Every Valet project will have the DB_PASSWORD automatically loaded. One less thing to add to your .env file.

Bonus: Manage it in your .dotfiles

If you manage your .dotfiles in a git repository like I do, make sure you don't commit this file as it contains a password. It's a local database password, so it's not too critical but if you're going to publish the password, you may as well remove the password of the root user!

A good way to handle this is to create a template in your repository, copy the file and inject the necessary secrets.

1export DB_PASSWORD="my-password"
2valet_env_file="$HOME/.config/valet/.valet-env.php"
3sed -E "s/PWD_PLACEHOLDER/$DB_PASSWORD/g" "path/to/template/valet-env.php" > "$valet_env_file"