ItSolutionStuff.com

Laravel Division by Zero Exception - Solved

By Hardik Savani • November 5, 2023
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: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Connect PostgreSQL Database in Laravel?

Read Now →

How to use Sqlite Database in Laravel?

Read Now →

How to Use Break And Continue In Laravel Blade Foreach?

Read Now →

Laravel Blade Foreach Last Element Example

Read Now →

How to Encrypt Decrypt Database Fields in Laravel?

Read Now →

How to Generate Secure Https URL from Route in Laravel?

Read Now →

Laravel Relationships with Optional() Helper Example

Read Now →

How to Send Mail using PHPMailer in Laravel?

Read Now →

Laravel Wordpress REST API Tutorial Example

Read Now →

How to Page Break in PDF using DomPDF Laravel?

Read Now →

Laravel 10 Generate PDF File using DomPDF Example

Read Now →