Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid The Divide by Zero Error Laravel Framework

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);
}
like image 407
Phil Nind Avatar asked Nov 30 '22 17:11

Phil Nind


1 Answers

Just add a simple condition:

return $tipslastmonth == 0 ? 0 : ($sumOfTheOddsLastMonth / $tipslastmonth);
like image 121
Thomas Ruiz Avatar answered Dec 03 '22 22:12

Thomas Ruiz