I'm getting response from an API in Laravel using HTTP client. And It takes some time. I just want to calculate that how much percentage of data is fetched from API. And when progressbar of 100% complete it means data is completely fetched and ready to show. So any solution for this?
How to calculate percentage while getting data from API response
919 Views Asked by Hammad Butt At
2
There are 2 best solutions below
0

if you are that flexible then you can do it this way ;) You can use queue job with livewire and tailwind css to achieve this goal.
- install tailwind.
- install livewire with this command
composer require livewire/livewire
. - run
php artisan make:livewire YourClassWire
to create livwire class, and you can find it under /App/Http/Livewire. - make YourClassWire somthing like this :
class YourClassWire extends Component
{
public $visibility;
// you need this to hide progress bar if it is 100% or 0
public $progress ;
// this will be your progress.
public $total ;
// this is your total job
protected $listeners = ['reresh']; // this will called from the view
public function mount()
{
$this->total = \DB::table('jobs')->count(); // you must change this if you have multiple queue with different names
$this->visibility = $this->total > 0 ? 'visible' : 'hidden' ; // we need it to show hide porgress ;
$this->progress = \DB::table('jobs')->count() * 100 / $this->total; // simple equation to get progress percentage
$this->render(); // you now call render each time the view refresh
}
public function refresh()
{
// this function will be responsible from updating the progress
$this->visibility = $this->total > 0 ? 'visible' : 'hidden' ; // we need it to show hide porgress ;
$this->progress = \DB::table('jobs')->count() * 100 / $this->total; // simple equation to get progress percentage.
}
public function render()
{
return view('livewire.your-class-wire',) // note this will created with command you executed earlier `php artisan make:livewire YourClassWire` and you can find it in view/livewire
->with('progress', $this->progress)
->with('visibility',$this->visibility);
}
}
<div wire:poll.2s="refresh">
<div class="{{$visibility}}">
<div class=" progress_main flex w-3/6 bg-gray-200 rounded-full h-1 mb-4 dark:bg-gray-700">
<!-- controll the width with the progress -->
<div class= "progressbar border-0 relative align-middle bg-gradient-to-r from-[#d72323] via-[#dddd03] to-[#248401] dark:bg-[#dcf5ff] h-1 rounded-full" style="width: {{ $progress }}%">
<div class="overflow-hidden absolute bottom-[-9px] flex items-center right-0 mr-[-60px] z-30 h-6 text-2xl text-[#f36d1f]">✈️
<!-- now this text icon will move to the end based on your progress -->
</div>
</div>
</div>
</div>
</div>
I hope this guide you to what you want..success
You could do some logic like:
or if you need to calculate average or something like that you can go
Note: If there are a lot of data in the JSON response, queues would be a good solution for it :)
Queues