Laravel Stats Helper
With laravel-stats-helper
you can get the statistics of two values or an array of values. It allows you to get the difference, percentage, change in percentage and an indicator whether the change is positive or negative. This helper could be useful in generating simple graphs or statistics for a dashboard or reporting page.
Requirements
- Laravel 8.x or 9.x
Laravel support
Version | Release |
---|---|
9.x | 1.1 |
8.x | 1.0 |
Installation
Install the package via composer:
composer require label84/laravel-stats-helper
Usage
use Label84\StatsHelper\Facades\StatsHelper;
$stats = StatsHelper::init(40, 60);
$stats->getOld(); // 40
$stats->getNew(); // 60
$stats->getDifference(); // 20
$stats->getPercentage(); // 150
$stats->getChangeInPercentage(); // 50% (it's a 50% increase)
$stats->isPositive(); // true
$stats->isNegative(); // false
You can use the StatsArrayHelper
to get the stats for multiple items.
use Label84\StatsHelper\Facades\StatsArrayHelper;
$colection = StatsArrayHelper::create([
'January' => 10,
'February' => 50,
'March' => 75,
'April' => 200,
'May' => 100,
])
->mapWithKeys(fn ($stats, $key) => [$key => $stats->getChangeInPercentage().'%']);
// Illuminate\Support\Collection
'January' => '0%', // (no previous value available)
'February' => '400%',
'March' => '50%',
'April' => '167%',
'May' => '-50%',
You can also set new values with the setPrev
and setNext
methods. This could be helpful in a for/foreach loop.
use Label84\StatsHelper\Facades\StatsHelper;
$stats = StatsHelper::init(50, 60);
$stats->getDifference(); // 10
$stats->setNext(100);
$stats->getOld(); // 60
$stats->getNew(); // 100
$stats->getDifference(); // 10
Tests
./vendor/bin/phpstan analyze
./vendor/bin/phpunit