Super Quick Tutorial: Artisan Command to Deploy Your Project

This is for small projects. For larger or distributed project you’re going to need a tool like Envoyer at the least, or preferably full CI/CD pipelines – there are loads of articles on this.

This is not best practice in most scenarios, and will incur downtime for your app.

The Problem / Situation

You want a quick and easy way to deploy your project, without any additional complexities and without CI/CD pipelines.

The Super Quick Solution

Create an Artisan command, something like system:deploy will probably suffice. The handle method will probably look something a bit like this;

$backup = $this->confirm("Would you like to take a backup before deploying?", true);

$branch = $this->ask("Which branch are you deploying?", "master");
$start = microtime(true);

$this->line("Taking app offline");
Artisan::call('down');

// This assumes that you have a system:backup command in place
if($backup === true){
    $this->comment("Taking backup");
    Artisan::call('system:backup');
    $this->line("Backup complete");
}

$commands = [
    // Grab what we need from Git and check it out
    'git fetch',
    'git checkout ' . $branch,
    'git pull',

    // Remove the dependency management directories, so we can run again fresh
    'rm -rf vendor/',
    'rm -rf node_modules/',

    // Install composer
    'composer install',

    // Run NPM commands
    'npm install',
    'npm run production'
];

// Output the commands, and run them for each of the above
foreach($commands as $exec){
    $this->line($exec);
    `$exec`;
}

// Run the migrations
$this->line("Running migrations");
`php artisan migrate --force`;

// Clear the cache
$this->line("Clearing cache");
Artisan::call('cache:clear');

// Clear the views
$this->line("Clearing views");
Artisan::call('view:clear');

// Clear the compiled classes
$this->line("Clearing compiled classes");
Artisan::call('clear-compiled');

// Clear the configuration
$this->line("Clearing configuration");
Artisan::call('config:cache');

// If you're running Horizon, kill it (you should have supervisor or equivalent running to pick it back up)
$this->line("Killing Horizon - so it can be restarted by supervisor");
Artisan::call('horizon:terminate');

// We're all done
$this->comment("Deployment Complete - Artisan UP");
Artisan::call('up');

// Output a quick line of how long it took to deploy
$finish = microtime(true);
$this->info(round($finish - $start, 3) . " seconds to deploy");

I'd love to hear your opinion on what I've written. Anecdotes are always welcome.

This site uses Akismet to reduce spam. Learn how your comment data is processed.