Minimize downtime when deploying new code to your Laravel site

I deploy my Laravel site using Ploi, but I was facing a problem: since I don’t use the zero-downtime option, how can I minimize downtime when deploying new code to my website?

NOTE: This article will be updated over time with any new tricks I discover so check back to see what else you can do. They should also work with all deployment tools like Laravel Forge and Deployer; I just happen to use Ploi.

Don’t recompile JS/CSS assets if they haven’t changed

There is no sense re-running yarn run prod if there’s nothing to do, so instead of just doing

yarn install --save
yarn run production

or

npm install --save
npm run production

let’s be intelligent about it:

# Dump the list of filenames changed in the last git commit
git diff --name-only HEAD HEAD~1 > /tmp/gitdiff.txt

# First, assume there were no changes
yarn=false

# Read the /tmp/gitdiff.txt file line by line....
while read line; do
    # The regex to search for CSS/JS/Vue/.lock/JSON/PHP files in the resources folder
    # We include PHP here in case you use PurgeCSS
    positiveMatch='^(resources\/|).*(css|js|vue|lock|json|php)$'
    negativeMatch='^(composer|public)'

    # Check to see if any those filetypes are listed 
    if  [[ $line =~ $positiveMatch && ! $line =~ $negativeMatch ]]; then 
        # ...and if so, set the yarn flag to true
        yarn=true
        echo $line
    fi
done < /tmp/gitdiff.txt

# If any changes were detected, run the necessary yarn commands
if $yarn ; then
    yarn install --save
    yarn run production
fi

# Cleanup
yarn=false
rm /tmp/gitdiff.txt    

And that’s how you can minimize downtime when deploying new code to your Laravel site!