How to catch a database insertion error in Laravel

Exception Handling

With PHP exception handling it's often much better to be specific. In many cases you might even be forced to be specific otherwise you won't see anything.

This code snippet explains how to catch a Laravel database query exception when generic exception handling doesn't produce the error:

use Illuminate\Support\Facades\Log;

...

try { 
   $results = \DB::connection("db_connection")
      ->select(\DB::raw("SELECT * FROM table"))
      ->first(); 
   } catch(\Illuminate\Database\QueryException $ex) { 
      Log::error($ex->getMessage()); 
}
lang-php

The key is to catch \Illuminate\Database\QueryException

Reference