Error handling in laravel using try and catch

While using applications sometimes we face errors like “Whoops, something went wrong” or get framework exception code which you can understand but the user can’t.

In Laravel we can handle those types of errors and give proper error explanations to users using try and catch.

When we try to get value from a null model instance then it will raise an error something like “trying to get property of non-object”. In this example, we will handle those types of errors.

Here, the concept of the example is to use the default Laravel User model for database search. The User model is automatically created by Laravel itself while creating a new Laravel project.

To understand this example, we have split it into below few steps.

  1. Creating Controller Methods
  2. View Creation for User Interaction
  3. Route Creation
  4. Testing our Example

Creating Controller Methods

Let’s assume you already have an application. The first thing we need to do is create a controller that will handle our logic for searching users. To create a controller enter the below command into your terminal :

php artisan make:controller SearchController

This command will create a new file at App\Http\Controllers\SearchContoller.php. Practically we will write all logic for the search controller into this file. So make the below changes to SearchController :

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Database\Eloquent\ModelNotFoundException; //Import
use Illuminate\Http\Request;

class SearchController extends Controller
{
    /**
     * Our search logic with exception handling
     */
    public function search(Request $request)
    {
        try {
            $user = User::findOrFail($request->input('user'));
        } catch (ModelNotFoundException $exception) {
            return back()->withError($exception->getMessage())->withInput();
        }
        return view('search', compact('user'));
    }
}

Here, we have created a search method that will handle user input and check user id exists in the database or not. If the user ID matches with the database then it will pass it to view Otherwise it will raise an error.

Creating Views for User Interaction

Here we need two views, the first view will take user input and the second view will display the user name and email address.

Here, we are going to modify the default welcome view. So Open resources\views\welcome.blade.php and modify as below :

<!DOCTYPE html>
<html>
<head>
     <title>Laravel try and catch example</title>
     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha512-rO2SXEKBSICa/AfyhEK5ZqWFCOok1rcgPYfGOqtX35OyiraBg6Xa4NnBJwXgpIRoXeWjcAmcQniMhp22htDc6g==" crossorigin="anonymous" />
</head>
<body>
     <div class="container mt-5">
          <div class="col-md-8 offset-2">
                <h2 class="text-center">Laravel Error Handling By codewolfy.com</h2>
                <div class="card mt-4">
                    <div class="card-header text-center">
                         <h3>Search for user by ID</h3>
                    </div>
                    <div class="card-body">
                        @if (session('error'))
                            <div class="alert alert-danger">{{ session('error') }}</div>
                        @endif
                        <form action="{{ route('user.search') }}" method="POST">
                            @csrf
                            <div class="form-group">
                                <label for="UserID">User ID</label>
                                <input type="number" class="form-control" name="user" id="user"  placeholder="Enter User ID" required>
                            </div>
                            <button type="submit" class="btn btn-primary">Submit</button>
                        </form>
                    </div>
               </div>
          </div>
     </div>
</body>
</html>

This view will show a form to the user which will ask for one parameter user id.

We need another view to display user information. So, create another view file under resources\views\search.blade.php and define the layout as below :

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha512-rO2SXEKBSICa/AfyhEK5ZqWFCOok1rcgPYfGOqtX35OyiraBg6Xa4NnBJwXgpIRoXeWjcAmcQniMhp22htDc6g==" crossorigin="anonymous" />
</head>
<body>
    <div class="container mt-5">
        <div class="col-md-8 offset-3">
            <h2 class="text-center">Laravel Try and Catch By codewolfy.com</h2>
            <div class="card mt-4">
                <div class="card-header">
                    <h3>User Detail</h3>
                </div>
                <div class="card-body">
                    <table class="bordered">
                        <tr>
                            <td>Name :</td>
                            <td>{{ $user->name }}</td>
                        </tr>
                        <tr>
                            <td>Email :</td>
                            <td>{{ $user->email }}</td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Route Creation

Lastly, we need to create a route that will handle the search operations. Add below lines to routes\web.php file :

Route::post('/search',[App\Http\Controllers\SearchController::class,'search'])->name('user.search');

Testing our example

Before testing please migrate your database. Then enter the below URL to test :

http://127.0.0.1:8000