Avoid division by zero Laravel Framework errors

I am trying to calculate some statistics on my Laravel site ... however when I execute the following code it gives me "Divide By Zero Error"

I understand why, because there are no records, so the calculation is 0 divided by 0

Is there a way that if it throws zero to echo "0" instead of throwing this 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);
}

      

+3


source to share


2 answers


Just add a simple condition:



return $tipslastmonth == 0 ? 0 : ($sumOfTheOddsLastMonth / $tipslastmonth);

      

+10


source


  • As you know, this error occurs because of 0 in your variable Just do this
if($tipslastmonth != 0)     
    $tipslastmonth = $sumOfTheOddsLastMonth / $tipslastmonth;  
else     
    $tipslastmonth = 0;

      



  1. When 0 is not encountered the part will work fine with my project
0


source







All Articles