How to catch a database insertion error in Laravel

Background

PHP exceptions are strange things. In many cases you can’t just catch the generic exception class and you have to be very specific. This article explains how to catch a Laravel database query exception.

use Log;

...

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

The key is to catch \Illuminate\Database\QueryException

Reference

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top