Laravel Division by Zero Exception - Solved

By Hardik Savani November 5, 2023 Category : Laravel

Hi Dev,

In this short tutorial, we will cover a division by zero exception laravel. you can understand a concept of division by zero exception laravel error. step by step explain division by zero error laravel. if you want to see an example of laravel divide by zero exception then you are in the right place.

Sometime we work with attempting to divide a number by zero will result in a "Division by zero" exception being thrown. You can handle this exception gracefully in your code to avoid crashes and provide a more user-friendly response. We need to resolve that it's call run time error. so we can solve by two ways. you can see the one by one solution with example.

Error Page:

Laravel Division by Zero Exception Solved using custom logic

you can see the controller code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$value = 10;

$denominator = 0;

$result = $denominator == 0 ? 0 : ($value / $denominator);

dd($result);

}

}

Laravel Division by Zero Exception Solved using DivisionByZeroError

you can see the controller code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DivisionByZeroError;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$value = 10;

$denominator = 0;

try {

$result = $value / $denominator;

} catch (DivisionByZeroError $e) {

$result = 0;

}

dd($result);

}

}

I hope it can help you...

Tags :
Shares