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.
Laravel also provides facality to log the basic information like below code.
1
|
Log::info("Coding 4 Developers");
|
In Laravel logs are stored in storage/logs directory.
You also can create the log on daily basis in Laravel by following steps:
open app.php which is inside the config directory.
1
|
'log' => env('APP_LOG', 'single'),
|
Change single to daily like below.
1
|
'log' => env('APP_LOG', 'daily'),
|