52 lines
1.4 KiB
PHP
52 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace App\Repositories\Core;
|
|
|
|
use Carbon\Carbon;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
Trait DateStats
|
|
{
|
|
public static function countByMonth($prev = 0)
|
|
{
|
|
$start = Carbon::now()->startOfMonth($prev);
|
|
$end = Carbon::now()->endOfMonth($prev);
|
|
return self::countByPeriod($start, $end);
|
|
}
|
|
|
|
public static function countByPeriod($start, $end, $field = 'created_at')
|
|
{
|
|
return self::getModel()->whereBetween($field, [$start, $end])->count();
|
|
}
|
|
|
|
public static function avgByMonth($prev = 0, $field = false)
|
|
{
|
|
$start = Carbon::now()->startOfMonth($prev);
|
|
$end = Carbon::now()->endOfMonth($prev);
|
|
return self::avgByPeriod($start, $end, $field);
|
|
}
|
|
|
|
public static function avgByPeriod($start, $end, $field)
|
|
{
|
|
$c = self::countByPeriod($start, $end);
|
|
return $c ? round(self::sumByPeriod($start, $end, $field) / $c, 2) : 0;
|
|
}
|
|
|
|
public static function sumByMonth($prev = 0, $field = false)
|
|
{
|
|
$start = Carbon::now()->startOfMonth($prev);
|
|
$end = Carbon::now()->endOfMonth($prev);
|
|
return self::sumByPeriod($start, $end, $field);
|
|
}
|
|
|
|
public static function sumByPeriod($start, $end, $field = 'created_at')
|
|
{
|
|
return self::getModel()->whereBetween($field, [$start, $end])->sum($field);
|
|
}
|
|
|
|
public static function getModel()
|
|
{
|
|
return new Model;
|
|
}
|
|
}
|