Implementation
Add the following code to your bootstrap/app.php file, before the return statement:
$envFile = '.env';
if (isset($_SERVER['HTTP_HOST']) && str_contains($_SERVER['HTTP_HOST'], 'alternativehost.test')) {
$envFile = '.env.althost';
}
Want to let it work with php artisan as well in symlinked directories?
if (isset($_SERVER['PWD']) && str_contains($_SERVER['PWD'], '/alternativehost')) {
$envFile = '.env.althost';
}This is probably dangerous. Check warnings below.
How It Works
The code checks two conditions:
- First, it checks if the HTTP host contains your specified domain (safer approach)
- Second, it checks the working directory path (riskier approach, but useful for CLI operations)
⚠️ Important Notes
- The second condition using
PWDis riskier as it relies on directory structure and might need additional security measures - Always ensure your alternative .env files are included in your
.gitignore - Remember to clear config cache after making changes:
php artisan config:clear
Best Practices
- Keep your .env files secure and never commit them to version control
- Use descriptive names for your alternative .env files
- Document the environment differences for your team
- Consider using Laravel’s built-in environment detection when possible
Last Updated on 5 March 2025
