DEV Community

David Llop
David Llop

Posted on • Originally published at davidllop.com on

Running old sites in Laravel Valet - Environment Variables

A few days ago my Homestead machine decided to die and not booting again (I'm totally sure I broke something, Joe P Ferguson does an amazing job with that Vagrant machine, the 2nd most downloaded on vagrant boxes site 😱)

The thing is, I already had Laravel Valet installed in my Macbook, so I thought I could run the project on that one for this time.

But old sites usually were made with Apache server in mind and they use environment variables and htaccess (I'll talk about this in another post).

Since Valet does not currently support custom .env files, I found a few custom ways of loading the variables, but all that methods messed up with the code and I don't want to be pending of deleting those lines from index.php before committing to repository. It's too risky.

But checking out the content of this pull request I thought about a similar approach, without touching nginx configuration.

As the official documentation suggest, I created a file called LocalValetDriver.php inside the app directory with the following content

class LocalValetDriver extends LaravelValetDriver
{
    /**
     * Determine if the driver serves the request.
     *
     * @param  string  $sitePath
     * @param  string  $siteName
     * @param  string  $uri
     * @return bool
     */
    public function serves($sitePath, $siteName, $uri)
    {
        return true;
    }

    /**
     * Get the fully resolved path to the application's front controller.
     *
     * @param  string  $sitePath
     * @param  string  $siteName
     * @param  string  $uri
     * @return string
     */
    public function frontControllerPath($sitePath, $siteName, $uri)
    {
        return $sitePath.'/public/index.php';
    }
}

Then inside frontControllerPath I load the environment variables:

public function frontControllerPath($sitePath, $siteName, $uri)
{
    $this->loadEnvironmentVariables();

    return $sitePath.'/public/index.php';
}

private function loadEnvironmentVariables()
{
    // all env variables here
    putenv('VAR=value');
    ...

}

Ignoring the file from repositories (optional)

The only remaining action is to add LocalValetDriver to your global gitignore. This action will prevent this file with sensible information (and also not project-related) to be uploaded to the repository.

In case you don't have a file called .gitignore_global in your home directory, you'll need to run this command first to link it with your git configuration

git config --global core.excludesfile ~/.gitignore_global

Add LocalValetDriver.php to this file

echo "LocalValetDriver.php" >> ~/.gitignore_global

Top comments (0)