Laravel 11 Try Catch in Controller Tutorial Example

Laravel 11 try catch statement example. In this tutorial, i am going to show you how to use try catch statements in Laravel 11 in controller for error handing with exceptions.

Laravel 11 Try Catch

The syntax represents the try..catch statement:

try {
    // run your code here
}
catch (exception $e) {
    //code to handle the exception
}

The try…catch statement is used to handle the errors.

Let’s take a look example of laravel try catch:

Find Product By Title

Let’s take look a very easy example, Here you have product table and find the product with it’s title.

You can handle errors using try…catch statement in laravel. See the following representation of try..catch.

If you are not checking for product exist or not in database, And you can directory pass data to your blade file.

So there has two case, first one is if the product is found, there were no errors, but if a product is not found, there will be display some errors on your search.blade.php file.

Go to .env file and set APP_DEBUG=false and then the browser will just show blank Whoops, looks like something went wrong. But that still doesn’t give any valuable information to our visitor.

If the product is not found and error occurs, so you can pass errors on your search.blade.php file with try..catch statement.

See the following example:

public function search(Request $request)
{
    try {
        $product = Product::where('title',$request->get('title'));
    } catch (ModelNotFoundException $exception) {
        return back()->withError($exception->getMessage())->withInput();
    }
    return view('product.search', compact('product'));
}

If you want to display an error in Blade file, you can do look like:

<h3 class="page-title text-center">Search by proudct title</h3>
@if (session('error'))
<div class="alert alert-danger">{{ session('error') }}</div>
@endif
<form action="{{ route('product.search') }}" method="POST">...</form>

Conclusion

In this laravel tutorial, you have learned how to use try catch statment in Laravel 11 application.

Recommended Laravel Tutorials

Leave a Comment