Setting a Folder Path Dynamically in Different Environments

Problem

You want to set a folder path absolutely, without hardcoding the absolute path.

Solution

Let’s say you want absolute file paths for your Assets sources, but said file paths might be different, depending on your environment.

We need to add a environment variable in general.php, as explained in the documentation.

'*' => [
    'environmentVariables' => [
        'basePathPublic' => realpath(dirname(__FILE__)).'/../../public/',
    ]
]

In your Assets Source configuration, prefix whatever relative path you have in the File System Path with the variable {basePathPublic}.

For example:

  • File System Path: {basePathPublic}/storage/images/
  • URL: /storage/images/

Discussion

The path is relative to general.php, so if your public path is different than the standard, your configuration must reflect that.