This tutorial is to learn how to handle and log the exceptions in Laravel. We will simply use try & catch to handle the exceptions in Laravel.
This is always good practice to handle the exceptions in any application to track the issue.
Laravel provides the following library to log the exceptions.
1
|
use Illuminate\Support\Facades\Log;
|
Now I'll demo the code to catch the exception and log it.
Here I have defined UserServiceProvider class and inside this class deleteUser() is a function to delete the user.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<?php
namespace App\Providers;
use App\Models\Users;
use Illuminate\Support\Facades\Log;
/**
* UserServiceProvider class conatains methods for user management
*/
class UserServiceProvider extends BaseServiceProvider {
public function __construct() {
}
public static function deleteUser($request) {
try {
Users::where('id', $request->id)->delete();
UserServiceProvider::$data['success'] = 1;
UserServiceProvider::$data['message'] = trans('messages.user_deleted');
} catch (\Exception $e) {
Log::error(__CLASS__ . "::" . __METHOD__ . " " . $e->getMessage());
UserServiceProvider::$data['message'] = trans('messages.server_error');
}
return UserServiceProvider::$data;
}
}
|
So here in catch part we are logging the exception. ...