Use Laravel's QueryException:
use Illuminate\Database\QueryException;
try {
$status = DB::table('post')->where('id', 2)->update([
'title' => 'new title',
'content' => 'new content'
]);
} catch (QueryException $e) {
//var_dump($e->getMessage())
\Log::error('QueryException: ' . $e->getMessage())
}
UPDATE:
Why laravel throw QueryException when something wrong happened with SQL executing. See this Logic in laravel's source code.
Class: \Illuminate\Database\Connection
/**
* Run a SQL statement and log its execution context.
*
* @param string $query
* @param array $bindings
* @param \Closure $callback
* @return mixed
*
* @throws \Illuminate\Database\QueryException
*/
protected function run($query, $bindings, Closure $callback)
{
$this->reconnectIfMissingConnection();
$start = microtime(true);
try {
$result = $this->runQueryCallback($query, $bindings, $callback);
} catch (QueryException $e) {
$result = $this->handleQueryException(
$e, $query, $bindings, $callback
);
}
......
}