ProgressBar callback trait for Laravel commands
A progress bar is an excellent way to have some feedback when you are writing and running long process using Laravel commands.
TL;DR Using the output object, we can start, advance and stop the Progress Bar.
According to the Laravel official documentation, this is only what you need to create a progress bar:
<?php | |
$users = App\User::all(); | |
$bar = $this->output->createProgressBar(count($users)); | |
$bar->start(); | |
foreach ($users as $user) { | |
$this->performTask($user); | |
$bar->advance(); | |
} | |
$bar->finish(); |
Pretty straight forward, although you can use a different approach to avoid repeating the same code over and over.
Creating ProgressBarCallback trait
The following trait has a method that receives two arguments, a countable
object and a callback
and what it does is to create the progress bar, then run the given callback for each one of the items in the countable
variable.
<?php | |
namespace App\commands; | |
trait ProgressionBarOutput | |
{ | |
public function runProcess(\Countable $countable, callable $callback) | |
{ | |
$bar = $this->output->createProgressBar(count($countable)); | |
$bar->start(); | |
foreach ($countable as $item) { | |
call_user_func($callback, $item); | |
$bar->advance(); | |
} | |
$bar->finish(); | |
$this->line(''); | |
} | |
} |
Here you can see a dummy example.
https://twitter.com/Jeffer_8a/status/1121164390655512577
You can learn more about the Laravel Artisan Console by reading the official documentation
https://laravel.com/docs/5.8/artisan
That's all!
I hope you like it.
Do you have any tips and tricks to share? Please reach out on Twitter.
Cheers 🍻