Yes, it is possible to serve multiple clients from a single Laravel installation and choose a different .env file based on the domain name. You can achieve this by dynamically loading the environment variables in the AppServiceProvider or a custom middleware. Here’s a step-by-step solution:
-
Create Multiple
.envFiles: Create different.envfiles for each client, for example:-
.env.client1 -
.env.client2 -
.env.client3
-
-
Modify
AppServiceProvider: In yourAppServiceProvider, you can add logic to load the appropriate.envfile based on the domain name.// app/Providers/AppServiceProvider.php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Dotenv\Dotenv; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { $this->loadEnvironmentFromDomain(); } /** * Register any application services. * * @return void */ public function register() { // } /** * Load environment variables based on the domain. * * @return void */ protected function loadEnvironmentFromDomain() { $domain = request()->getHost(); switch ($domain) { case 'client1.example.com': $envFile = base_path('.env.client1'); break; case 'client2.example.com': $envFile = base_path('.env.client2'); break; case 'client3.example.com': $envFile = base_path('.env.client3'); break; default: $envFile = base_path('.env'); break; } if (file_exists($envFile)) { $dotenv = Dotenv::createImmutable(base_path(), $envFile); $dotenv->load(); } } } -
Update
config/app.php: Ensure that theAppServiceProvideris registered in yourconfig/app.phpfile.'providers' => [ // Other Service Providers App\Providers\AppServiceProvider::class, ], -
Clear Configuration Cache: If you have configuration caching enabled, you need to clear it to ensure the changes take effect.
php artisan config:clear -
Test Your Application: Access your application using different domain names and verify that the correct environment variables are loaded.
By following these steps, you can dynamically load different .env files based on the domain name, allowing you to serve multiple clients from a single Laravel installation.