In this tutorial, we will see how to use try catch in laravel. You can easily use try catch in laravel.
Given below is the step-by-step process for how to handle errors.
Step 1: Create Route
routes/web.php
Route::get('/users', 'UserController@index')->name('users.index');
Route::post('/users/search', 'UserController@search')->name('users.search');
Step 2: Create Controller
app/http/controller/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('users.index');
}
public function search(Request $request)
{
try {
$user = User::findOrFail($request->input('user_id'));
} catch (ModelNotFoundException $exception) {
return back()->withError($exception->getMessage())->withInput();
}
return view('users.search', compact('user'));
}
}
Step 3: Create Blade File
/resources/views/users/index.blade.php
<!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-2">
<h2 class="text-center">laravel try catch Example - Rathorji.in</h2>
<div class="card">
<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('users.search') }}" method="POST">
@csrf
<div class="form-group">
<input id="user_id" name="user_id" class="form-control" type="text" value="{{ old('user_id') }}" placeholder="User ID">
</div>
<input class="btn btn-info" type="submit" value="Search">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
/resources/views/users/search.blade.php
<!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 catch Example - Rathorji.in</h2>
<div class="card">
<div class="card-header text-center">
<h3>User Detail</h3>
</div>
<div class="card-body">
<table class="borded">
<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>
I hope this example helps you.