Laravel Error Handling with Exception and Try Catch

Hello Artisan 

In this Laravel error handling tutorial i will show you how we can handle error using laravel try catch and laravel exception class. We will use ModelNotFoundException to show our example.

Simply i will use User model to search user by requested id, if there is no user then i will show the error from our custom exception class. If you don't know how to use csutom exception class then this tutorial is for you. So in this tutorial i decided to write a step-by-step article of how to handle errors in elegant way and present proper error information to the visitor. 

So let's start our error handling with exception class tutorial.

 

Step 1 : Create Routes

We need to routes one is for view form and another is for searching user.

routes/web.php

Route::get('/', '[email protected]')->name('users.index');
Route::post('/', '[email protected]')->name('users.search');

 

Step 2 : Create Controller

We have to create TestController to add our two method. So create TestController and update it like below.

app/Http/Controllers/TestController.php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\ModelNotFoundException;  

class TestController extends Controller
{
    public function index()
    {
        return view('welcome');
    }

    public function search(Request $request)
    {
        $user = User::find($request->input('user_id'));
       
        return view('search', compact('user'));
    }
}

 

Step 3 : Create Blade File

In this step we need to create two blade file. One is for showing form and anther is for displaying searched data. So create those both file.

resources/views/welcome.blade.php

 

resources/views/search.blade.php

 

Now have a look on the controller search method. We’re not checking for user existence, so if there is no user from requested id, then laravel will show error like below image.

laravel-exception-with-custom-message

 

We’re not checking for user existence. Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:

 

We have to know the exception type and class name that it would return. In case of findOrFail() it will throw an Eloquent exception ModelNotFoundException, so we have to do this. Now update your controller like below.

app/Http/Controllers/TestController.php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\ModelNotFoundException;  

class TestController extends Controller
{
    public function index()
    {
        return view('welcome');
    }

    public function search(Request $request)
    {

        try {

          $user = User::findOrFail($request->input('user_id'));

	    } catch (ModelNotFoundException $exception) {

	       return back()->withError($exception->getMessage())->withInput();
	    }

        return view('search', compact('user'));
    }
}

 

Now you will see the error like below instead of before error messages.

laravel-error-handling-best-practices

 

You can also use throw exception to show error. To do it update you test controller search method like below.


namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\ModelNotFoundException;  

class TestController extends Controller
{
    public function index()
    {
        return view('welcome');
    }

    public function search(Request $request)
    {
        
        $user = User::find($request->input('user_id'));

        if (!$user) {
           throw new \Exception("User not found by ID {$request->input('user_id')}");
        }
       
        return view('search', compact('user'));
    }
}

 

Now if there is no user from requested id, then i will throw an exception error. Hope you will understand.

 

Recommended: Laravel 7.x Daily Monthly Weekly Automatic Database Backup Tutorial

 

Hope it can help you.