Robin
Robin

Reputation: 1587

Division by zero in Laravel 5.1

I've a problem which I can not fix in Laravel 5.1. I have "Division by zero" as an error in this code:

public static function GetAvgVisits()
    {
      $average_visits = DB::table('tracker_sessions')->where('is_robot', '=', 0)
                        ->whereRaw("created_at between '".Carbon::now()->startOfMonth()."' and '".Carbon::now()->endOfMonth()."'")
                        ->count(DB::raw('DISTINCT client_ip')) / (int)Carbon::now()->diff(Carbon::now()->startOfMonth())->format('%a') + 1;

      return round($average_visits);
    }

And I just can't find the correct solution. Can someone help me out?

Upvotes: 1

Views: 3113

Answers (1)

Elwin Arens
Elwin Arens

Reputation: 1622

The division precedes the + 1, so if the + 1 is there to prevent a zero division, then add parentheses before / and after + 1:

public static function GetAvgVisits()
    {
      $average_visits = DB::table('tracker_sessions')->where('is_robot', '=', 0)
                        ->whereRaw("created_at between '".Carbon::now()->startOfMonth()."' and '".Carbon::now()->endOfMonth()."'")
                        ->count(DB::raw('DISTINCT client_ip')) / ((int)Carbon::now()->diff(Carbon::now()->startOfMonth())->format('%a') + 1);

      return round($average_visits);
    }

A bit hard to see, but i have added these:

/ ( (int)Carbon::now()->diff(Carbon::now()->startOfMonth())->format('%a') + 1 );

Upvotes: 2

Related Questions