/var/log

One Laravel codebase with multiple databases and hostnames

What we want to achieve:

  • Using one Laravel codebase that serves multiple hostnames and databases
  • Each codebase should have a separate storage and bootstrap/cache directory
  • And of course each codebase should have its own environment file

These are the steps needed to accomplish this.

Symlink to codebase

Each hostname should have be a symlink to the original codebase. For example our codebase is in /var/www/codebase and if we have a new hostname we should create a symlink to this codebase, for example a symlink /var/www/host1 pointing to /var/www/codebase.

Now we can point to this symlink in the webserver config.

Loading environment file and set storage path

To load a specific environment file and use a specific storage path, add the following code to the bootstrap/app.php file just below the first lines where the $app is created:

// This line is already present:

$app = new Illuminate\Foundation\Application(
    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);

// Add this:

$envFile = '.env.host1';
// Note that loadEnvironmentFrom excepts a path relative to the base path
$app->loadEnvironmentFrom($envFile);

$storagePath = base_path('storage.host1');
// Note that useStoragePath expects an absolute path
$app->useStoragePath($storagePath);

The bootstrap cache directory

The bootstrap/cache directory is used to store cached config, routes and some other resources. These cached files are created after you do for example: php artisan config:cache. This command will create a bootstrap/cache/config.php file with all config settings for performance reasons. At the same time this will invalidate ALL calls to env() except those in the files in the config directory.

Each and every hostname MUST have its own bootstrap/cache directory. Otherwise the bootstrap/cache/config.php file will only have the settings of the last call to php artisan config:cache!

To use different bootstrap/cache directories for each hostname, add the below variables to the .env file of this hostname.

MY_BOOTSTRAP_CACHE_PATH="/var/www/html/bootstrap/cache"
APP_CONFIG_CACHE="${MY_BOOTSTRAP_CACHE_PATH}/config.php"
APP_ROUTES_CACHE="${MY_BOOTSTRAP_CACHE_PATH}/routes.php"
APP_EVENTS_CACHE="${MY_BOOTSTRAP_CACHE_PATH}/events.php"
APP_SERVICES_CACHE="${MY_BOOTSTRAP_CACHE_PATH}/services.php"
APP_PACKAGES_CACHE="${MY_BOOTSTRAP_CACHE_PATH}/packages.php"

Tag: , | Category: