If you're of the few folks out there that uses Capistrano to deploy their Laravel projects (we DO exist!), this article will hopefully be useful for you.
Versioning your app is great for a number of reasons, and there are some use cases for needing access to this value in a production environment.
In my particular case, I maintain a large dashboard which receives frequent updates, and having the version number displayed in the footer helps as a quick visual reference.
The Approach
Fortunately, this is not a particularly complicated task. Here's what we need to do:
Ensure an APP_VERSION parameter exists in the .env file stored in the secrets directory within the production environment.
Add a task to the deploy.rb file which will prompt the user for a version string, then rewrite the line in the .env file within the release directory.
Adding The Task
Here's the task code that I use for this purpose:
task :set_version do
ask(:app_version, "")
on roles(:laravel) do
execute :sed, "-i 's/^APP_VERSION.*/APP_VERSION=#{fetch(:app_version)}/' #{release_path}/.env"
end
end
Let's break down what's going on in the above snippet.
We are defining our task as
set_version, which when executed, prompts the user for an app version string.Once the value is received, it is stored in the
app_versionconfiguration variable.This task sits within a
laravelnamespace in the file, which explains theon roles(:laravel)line.The
executedirective is for a 1-line bash command, usingsed, to perform an inline edit of the.envfile located in the root of the release path.The
sedcommand which perform a regex match forAPP_VERSIONand replaces the entire line with the new value.Still within the
sedcommand, we havefetch(:app_version), which is the configuration value we stored earlier (mentioned in point 1).
Finally, we can set the task to run like in the example below:
namespace :deploy do
after :updated, "laravel:set_version"
end
Clearing Config Cache
You will of course need to clear the config cache within the release directory to pick up the change to the .env file.
It's likely you are already doing this in some way; my preferred method is to use a task like this:
task :clear_config do
on roles(:laravel) do
within release_path do
execute :php, "artisan config:cache"
execute :php, "artisan view:cache"
execute :php, "artisan route:cache"
execute :php, "artisan cache:clear"
end
end
end
Just be sure to clear the config cache after the app version task has been run.
Thanks!
I appreciate you taking the time to read this; hopefully it helps someone along the way.
Top comments (0)