Error handling In laravel with try and catch

While using applications sometimes we face error like "Whoops, something went wrong" or get framework exception code which you can understand but user can't.

In Laravel we can handle those type of errors and give proper error explanation to user using try and catch.

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

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

To understand this example, we have spilt it into below few step.

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

Creating Controller Methods

Let's assume you already has application. First thing we need to do is create controller which will handle our logic for searching user. For creating controller enter below command into you terminal :

php artisan make:controller SearchController

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


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 search method will handle user input and check user id exist in database or not. If user id match with database then it will pass it to view Otherwise it will raise an error.

Creating Views for User Interaction

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

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

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

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

Route Creation

Lastly we need to create route which will handle search operation. Add below lines to routes\web.php file :


Testing our Example

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

I hope this example will help you to understand error handling and if you have any queries then fell free to comment.

Share your thoughts

Ask anything about this examples