This is LARA Nepal. X

Mastering Laravel Console Commands: Implementing A Progress Bar

Published on April 9, 2024 by

Mastering Laravel Console Commands: Implementing a Progress Bar

Progress Bar

A progress bar is a graphical user interface element used to visualize the progress of a task. It typically consists of a horizontal bar that gradually fills up as the task progresses, indicating the percentage of completion.

withProgressBar()

$this->withProgressBar(
User::all(),
function (User $user) {
sleep(seconds: 1);
}
);

The withProgressBar() method is used to create a progress bar while iterating over a collection. In this case, it iterates over all users fetched from the database (User::all()). Inside the closure function passed to withProgressBar(), each user is processed. Here, it seems to simulate some task with a sleep() function call to pause execution for 1 second.

progress()

progress(
label: 'Loading User',
steps: User::all(),
callback: function (User $user)
{
sleep(1);
}
);

Another progress bar implementation utilizing the progress() function from Laravel Prompts package. It takes three arguments:

  • label: A string label indicating what the progress is for, in this case, 'Loading User'.
  • steps: The steps to iterate over, here again all users are fetched using User::all().
  • callback: A closure function that gets executed for each step. Similar to withProgressBar(), it also simulates some processing with a sleep() function call.

Concusion

In summary, this command demonstrates two different approaches to implementing progress bars in Laravel console commands. The withProgressBar() method is a built-in Laravel feature, while the progress() function originates from a third-party package, Laravel Prompts.

Discussion

Login or register to comment or ask questions

No comments or questions yet...