Laravel store exception in database

Mohit Mehta
Feb 15, 2019 · 2 min read

For bug free system we must look into every exceptions. In multi user system it’s hard to keep track on every exceptions. So here is a method by which you can store every exceptions in database.

Step 1. Create a new table with columns (user_id, action, exception and timestamps)

Step 2. Create New model for above table. For example I am giving name DbLog.

Step 3. Create new exception handler LogData.php and paste below code.



namespace App\Exceptions;

use Exception;
use Illuminate\Support\Facades\Auth;
use App\DbLog;
class LogData extends Exception
* Report the exception.
* @return void
public function report(){

* Render the exception into an HTTP response.
* @param \Illuminate\Http\Request
* @return \Illuminate\Http\Response
public function render($request, Exception $exception){
$log = new DbLog;
$log->user_id = Auth::user()->id;
$log->action = $request->fullUrl();
$log->exception = $exception;
return \Redirect::back()->with('error', 'Something Went Wrong.');

Here render function will store each exception in our table with user id of current logged in user. Action column will have complete url of page/method where exception occurred. After storing exception it will return on same page with error message. So user will see only error message instead of whole exception.

Step 4. Edit “render” function of Handler.php.


public function render($request, Exception $exception)
if ($exception instanceof \App\Exceptions\LogData) {
return $exception->render($request, $exception);
return parent::render($request, $exception);

Here we have checked if exception is type of LogData (which we’ll throw in next step) then it will pass request to handler.

Step 5. Now we can use this exception handler anywhere with try catch block. Below is the example.

// your code goes here...
}catch (\Exception $e) {
throw new \App\Exceptions\LogData($e);

So now you can check how is your system working.

More From Medium

Related reads

Related reads

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade