How To Handle Exception in Laravel 10 Example Tutorial

Reading Time: 5 minutes
309 Views

Exception handling is an important part of web application development because it ensures that mistakes are handled gracefully, preventing disruptions to the user experience. Laravel 10 includes a sophisticated exception handling system to assist you in dealing with various types of issues. With real examples, we will walk you through the steps of managing exceptions in Laravel 10.

When something goes wrong in your application, you may intercept and manage exceptions gracefully by giving custom replies, reporting failures, and taking relevant steps.

Read More: Laravel 10 Livewire Multistep Form Wizard Tutorial

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

What is an Exception in Laravel?

Exceptions serve the same basic role in Laravel as they do in PHP, but Laravel extends and improves PHP’s exception handling capabilities to give a more organised and expressive manner to deal with failures and exceptional situations within the framework.

Laravel HTTP Exceptions,

Laravel includes a set of HTTP exception classes for dealing with HTTP-related issues. NotFoundHttpException, ModelNotFoundException, ValidationException, and other exceptions are among them. These classes make it easy to gracefully handle HTTP-specific failures.

Laravel Exception Try Catch Block

To handle exceptions gracefully in Laravel, as in PHP, you may use a trycatch block. This is a crucial strategy for dealing with errors and unusual circumstances in your Laravel application.

Here’s how you can use the trycatch block in Laravel:

try {

    // Code that may throw an exception

} catch (\Exception $e) {

    // Handle the exception here
}

Let’s go over the steps,

The try block is where you put the code that may throw an exception. This is where you put potentially problematic code that might cause errors or exceptions.

Read More: How To Get Set Delete Cookie in laravel 10 Tutorial

The catch block comes after the try block and is in charge of catching and handling exceptions that occur within the try block. You indicate how you wish to respond to the exception in the catch block.

How To Handle Exception in Laravel?

Here, we will consider a small program where we write a code inside controller.

It checks a variable, if exists then Okay else generate an error / exception.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Exception;

class HomeController extends Controller
{
    public function index()
    {
        try {
            $user = User::find($input['id']);
        } catch (Exception $e) {

            $message = $e->getMessage();
            var_dump('Exception Message: ' . $message);

            $code = $e->getCode();
            var_dump('Exception Code: ' . $code);

            $string = $e->__toString();
            var_dump('Exception String: ' . $string);

            exit;
        }

        return response()->json($user);
    }
}

Add Route

Open web.php file /routes folder. Add this route into it.

//...

use App\Http\Controllers\HomeController;

Route::get('data', [HomeController::class, 'index']);

Application Testing

Run this command into project terminal to start development server,

php artisan serve

Read More: Laravel 10 Livewire DataTable Pagination Package Tutorial

URL: http://127.0.0.1:8000/data

That’s it.

We hope this article helped you to learn How To Handle Exception in Laravel 10 Example Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more