I am trying to calculate some stats on my Laravel site...however when I execute the following code it is giving me a 'Divide By Zero Error'
I understand why because there are no records so the calculation is 0 divide 0
Is there a way that if it eqauls zero to echo '0' rather than throw up that error
Controlller
private function getAverageOddsForLastMonth()
{
$firstDayOfLastMonth = new Carbon('first day of last month');
$lastDayOfLastMonth = new Carbon('last day of last month');
$tipslastmonth = Tip::whereBetween('tip_date',
[
$firstDayOfLastMonth,
$lastDayOfLastMonth
]
)->count();
$sumOfTheOddsLastMonth = Tip::whereBetween('tip_date',
[
$firstDayOfLastMonth,
$lastDayOfLastMonth
]
)->sum('odds');
return ($sumOfTheOddsLastMonth / $tipslastmonth);
}
Just add a simple condition:
return $tipslastmonth == 0 ? 0 : ($sumOfTheOddsLastMonth / $tipslastmonth);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With