Simplifying Laravel Upgrade Tasks: A Guide to Automating Your Development Workflow

Simplifying Laravel Upgrade Tasks: A Guide to Automating Your Development Workflow

Written by Supernova3339 on Jun 14th, 2023 Views Report Post

As Laravel developers, we know that upgrading our applications can be a pain. There are always a bunch of tasks like building assets, running database migrations, and clearing your application's various caches. These tasks can be time-consuming, repetive, and, at an great risk of human error.

But, there's great news! Laravel makes it easy to automate these tasks using custom commands. In this article, I'll show you how to create a custom command that will simplify your upgrade workflow.

Why Should We Automate Our Upgrade Tasks?

Before we get started, let's talk about why automating our upgrade tasks is a big deal. As your Laravel app grows and evolves, you'll make changes that require updating assets, your database, even configuration files! Doing this manually can be time-consuming and at high risk of human error. By automating the upgrade process, you can:

  • Save time: Automation eliminates the need for manual intervention, allowing you to focus on more important aspects of development.
  • Ensure consistency: Automated tasks are executed in a standardized manner, reducing the risk of mistakes caused by human error.
  • Reduce errors: Automation minimizes the chances of missing a step or executing tasks in the wrong order, resulting in a more reliable upgrade process.

Introducing the Upgrade Command

To automate upgrade tasks, we'll create a custom command in Laravel under our app\Console\Commands\UpgradeCommand that encapsulates the necessary steps. This command will handle building assets, running migrations, and clearing caches seamlessly. Let's explore the code in detail, line by line:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;

class UpgradeCommand extends Command
{
    protected $signature = 'upgrade {--force : Force migrations}';
    protected $description = 'Perform upgrade tasks';

    protected $force;

    public function handle()
    {
        $this->force = $this->option('force');

        $this->output->title('Starting upgrade tasks...');

        $this->runTasks();

        $this->output->success('Upgrade tasks completed.');
    }

    protected function runTasks()
    {
        $this->buildAssets();        // Build assets with npm run build
        usleep(1000000);
        $this->runMigrations();      // Run database migrations
        usleep(1000000);
        $this->clearConfigCache();   // Clear configuration cache
        usleep(1000000);
        $this->clearViewCache();     // Clear view cache
        usleep(1000000);
    }

    protected function buildAssets()
    {
        $this->output->write('Building assets...');

        exec('npm run build', $output, $status);

        if ($status === 0) {
            $this->output->write(' [' . $this->green('✔') . ']', true); // Successful task (green checkmark)
        } else {
            $this->output->write(' [' . $this->red('✘') . ']', true); // Failed task (red cross)
        }
    }

    protected function runMigrations()
    {
        $this->output->write('Running database migrations...');

        Artisan::call('migrate', ['--no-ansi' => true, '--force' => $this->force]);
        $exitCode = trim(Artisan::output());

        if ($exitCode === 'INFO  Nothing to migrate.' || strpos($exitCode, 'Migration table created successfully') !== false) {
            $this->output->write(' [' . $this->green('✔') . ']', true); // Successful task (green checkmark)
        } elseif (strpos($exitCode, 'Migration(s) are ready to be migrated') !== false) {
            $this->output->write(' [' . $this->green('✔') . ']', true); // Successful task (green checkmark)
        } else {
            $this->output->write(' [' . $this->red('✘') . ']', true); // Failed task (red cross)
        }
    }

    protected function clearConfigCache()
    {
        $this->output->write('Clearing configuration cache...');

        Artisan::call('config:clear');
        $this->output->write(' [' . $this->green('✔') . ']', true); // Successful task (green checkmark)
    }

    protected function clearViewCache()
    {
        $this->output->write('Clearing view cache...');

        Artisan::call('view:clear');
        $this->output->write(' [' . $this->green('✔') . ']', true); // Successful task (green checkmark)
    }

    protected function green($text)
    {
        return "\033[32m" . $text . "\033[0m"; // Green color code for successful tasks
    }

    protected function red($text)
    {
        return "\033[31m" . $text . "\033[0m"; // Red color code for failed tasks
    }
}

If you've setup the command correctly, running it should return the following: example.png

Understanding The Code

Now, let's break down the code and understand each function's purpose:

  1. handle(): This function serves as the entry point for the command. It retrieves the --force option value, displays a friendly message to inform users about the upgrade process, calls the runTasks() method to execute the upgrade tasks, and finally displays a success message when all tasks are completed.

  2. runTasks($force): This function orchestrates the execution of the upgrade tasks in a sequential manner. It calls the relevant functions for building assets, running migrations, and clearing caches.

  3. buildAssets(): This function takes care of building assets by executing the npm run build command using the exec() function. It provides feedback to the user by displaying a success or failure message based on the execution status.

  4. runMigrations($force): This function handles running database migrations. It utilizes Laravel's Artisan::call() method to execute the migrate command. It captures the output and provides appropriate feedback to the user.

  5. clearConfigCache(): This function clears the configuration cache using the Artisan::call('config:clear') command, ensuring that any configuration changes take effect.

  6. clearViewCache(): This function clears the view cache using the Artisan::call('view:clear') command, allowing any view changes to be reflected.

Why This Is Important For Your Laravel Application

Automating upgrade tasks in your Laravel application can have a significant impact on your overall development workflow. Here's why it's important:

  1. Streamlined workflow: By automating repetitive and time-consuming tasks, you can streamline your development process and focus on more critical aspects of your application.

  2. Enhanced productivity: Automation saves you valuable time and effort. You can perform upgrades more efficiently, allowing you to deliver new features and improvements to your users at a faster pace.

  3. Consistency and reliability: Automating upgrade tasks ensures that they are executed in a consistent and reliable manner. It reduces the risk of human error and helps maintain the integrity of your application.

  4. Error reduction: With automated tasks, the chances of missing a step or executing tasks in the wrong order are significantly reduced. This leads to a more reliable upgrade process and fewer errors in your application.

The custom command we've created builds assets, runs migrations, and clears your application's various caches, which can save you a lot of time. This helps make sure that you are free to develop and not worry about repetitive tasks that can slowdown your development workflow. This leads to less distractions allowing you to get things done!

Comments (0)