Header image of How to use env variables with Laravel Envoy scripts

Tested on Laravel 9.3 and Laravel Envoy 2.8

I use Laravel Envoy in some projects (including in this open sourced blog) to deploy directly from the commandline. While some of these projects maybe should use ci-pipeline (and surely will) I also like the simplicity of Envoy from time to time.

Just commit locally, run your tests and deploy all in one go.

I recently was happy to notice, that you can even use all Laravel helper functions inside scripts – but sadly, the env() command was not working

// ...

// this outputs "HELLO WORLD" on the server, that's cool! 🙂
@task('deploy', ['on' => 'web'])
    echo "{{str('hello')->upper()}}";
@endtask

// this outputs nothing 😢
@task('deploy', ['on' => 'web'])
    echo "{{env('APP_URL')}}";
@endtask

I guess that is the case because Laravel Envoy is set to be more of a framework-agnostic SSH solution for PHP and the LoadEnvironmentVariables class is deeply wired into the kernel of a Laravel application.

Luckily, you can load the .env content in the @setup method like described in the docs of underlying library phpdotenv

@setup
    $dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
    $dotenv->load();
@endsetup

// ...

You now are able to create a deployment script that uses variables from your .env file via the env() helper!

Keep in mind, that inside the @task ... @endtask block we have to use Blade-style, when defining the @servers we use pure PHP:

@setup
    $dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
    $dotenv->load();
@endsetup

@servers(['web' => [env('DEPLOY_USER') . '@' . env('DEPLOY_HOST')]])

@task('deploy', ['on' => 'web'])
    cd {{ env('DEPLOY_LOCATION') }}
    git pull
    npm install
    npm run prod
    compsoser install --no-dev
    php artisan cache:clear
    php artisan config:clear
@endtask

We are now able to hide away either sensitive or irrelevant information and put it into our .env 🎉

Thanks to Amit who wrote an article about this that led my on the right track, but the solution was not completely working for me.

So long! Simon

Read more posts
List image of the post How to test static pages automatically in Laravel Read more
Written 1 month ago
3 min read

How to test static pages automatically in Laravel

I developed a way to automatically crawl and test big parts of your Laravel application.

With just one line of code, you can now write a "peace of mind" test that gives you a lot of confidence.

Read more
List image of the post Your Tool is not the Problem - Your Workflow is Read more
Written 1 month ago
3 min read

Your Tool is not the Problem - Your Workflow is

A few (meta) thoughts on the search for the best project management tool.

Usually, the chaos you'll find in a software is a quite accuarate representation of your teams' communication skills - and also a big chance for improvement.

Read more
Back to all posts