In this tutorial you will learn about the Laravel 8 Try Catch in Controller Tutorial Example and its application with practical example.
In this How to Use try catch In laravel Example TutorialI will show you How to Use try catch In laravel.In this tutorial you will learn to use try catch exception handling in laravel framework. While working or developing application with Laravel framework, you may encounter many errors. It is very important to handle these errors properly in order to build safe and error free laravel application. In laravel you can use try catch statement for proper error handling in laravel.
Laravel 8 Try Catch in Controller Tutorial Example
Below is the syntax that represents the try..catch statement:
1 2 3 4 5 6 |
try { // run your code here } catch (exception $e) { //code to handle the exception } |
The try…catch statement is used to handle the errors.
Find Product By Title
Let’s take a look example of laravel try catch. Here you have product table and find the product with it’s title. So you have the following method in controller to find product by it’s title:
1 2 3 4 5 6 7 8 9 |
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')); } |
With try…catch we have implemented error handling in the above example code. Now if there is no error we can directly pass product data to blade file. But if there is error we can pass errors to blade file. If you want to display an error in Blade file, you can do look like:
1 2 3 4 5 6 7 |
<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> |
Note:- DO remember to set APP_DEBUG=false in .env file.