Add elapsed and estimated time to Laravel (and Symfony) console commands

You can add the elapsed and estimated time to your Laravel and Symfony console commands with just a flag!

Created on July 2021

Add elapsed and estimated time to Laravel (and Symfony) console commands

Laravel Artisan Console is a powerful functionality to write your console commands, also thanks to Symfony Console Component which represents the base engine for them.

One feature I always wanted, but found out it exists only recently, is the estimated time (ETA): basically how much time remains until the command finishes.

And as I said it's already a thing in the Console Component and the best part is that it could not be easier to implement!

You basically have two solutions:

  1. Run your command with -vv flag at the end, for example php artisan mycommand -vv and, automatically, your Progress Bar inside the command will show the elapsed and estimated time. Easy, right? The only "cons" I can think of is that every other component that uses the verbosity flag will be very verbose.
  2. To set only the Progress Bar as verbose, you can invoke the setFormat() method passing very_verbose as value. Take the following example, where we create a bar and set its verbosity:
<?php

namespace App\Commands;

use Illuminate\Console\Command;

class ProgressBar extends Command
{
    /**
     * The signature of the command.
     *
     * @var string
     */
    protected $signature = 'progressbar';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $data = range(1, 10);

        $bar = $this->output->createProgressBar(count($data));
        $bar->setFormat('very_verbose');
        $bar->start();

        foreach ($data as $item) {
            // Do something here

            $bar->advance();
        }

        return 0;
    }
}

Simple, right? Now if you run php artisan progressbar you should see an output similar to this post thumbnail, but compressed in only one line.

You can discover more about Progress Bars in the Symfony docs: https://symfony.com/doc/current/components/console/helpers/progressbar.html#built-in-formats

Next

How Ionic and Directus helped me start volunteering

Previous

Time travel after each Laravel Factory