CodeIgniter 4: try/catch does not catch a failed insert in the model
Duplicate entry '...' for keyShort answer
CodeIgniter throws a DatabaseException on a failed query only when DBDebug is true, and inside a transaction it does not throw unless you ask. With DBDebug off, the insert just returns false. Turn DBDebug on, catch DatabaseException, or read the error with $db->error().
Fix it fast
1Find out which cause you have
Check the DBDebug value of the database group your model uses. It decides whether a failed query throws.
grep -n "DBDebug" app/Config/Database.php2Match what you see, then jump to its fix
What does the error look like?
Duplicate entry '...' for keyDatabaseException
Cause 1 of 3
DBDebug is false, so nothing is thrown
1Check
DBDebug controls whether database errors throw exceptions. The default group ships with it set to true, so look for a false in your own config or in an environment override.
grep -rn "DBDebug" app/Config/2Fix
Set DBDebug to true for the group, and catch the exception.
use CodeIgniter\Database\Exceptions\DatabaseException;
try {
$this->insert($data);
} catch (DatabaseException $e) {
log_message('error', $e->getMessage());
}3Verify
Insert the same unique value twice; the second call lands in the catch block.
echo $e->getMessage(); // inside the catch blockConfirmed by codeigniter.com
Cause 2 of 3
The insert runs inside a transaction
1Check
Since 4.3.0, a failed query inside a transaction does not throw by default, even with DBDebug on.
grep -rn "transStart\|transBegin" app/2Fix
Call transException(true) before transStart, and catch DatabaseException outside the block. The transaction is rolled back before it throws.
try {
$this->db->transException(true)->transStart();
$this->insert($data);
$this->db->transComplete();
} catch (DatabaseException $e) {
// already rolled back
}3Verify
A duplicate insert now reaches the catch block and leaves no partial rows.
echo $e->getMessage(); // inside the catch blockConfirmed by codeigniter.com
Cause 3 of 3
You want to handle the error without an exception
1Check
With exceptions off, a failed query does not throw. The error stays on the connection, where the code and message can be read.
grep -rn "->error()" app/2Fix
After the insert, read the code and message from the connection's error method. MySQL uses code 1062 for a duplicate entry.
$this->insert($data);
$error = $this->db->error(); // keys: code, message
if ($error['code'] === 1062) {
// duplicate value
}3Verify
A duplicate insert gives code 1062 in the array.
echo $e->getMessage(); // inside the catch blockConfirmed by codeigniter.com
How do I stop it coming back?
- Decide per environment whether errors throw, and write it down in the database config.
- Add a unique index and handle the duplicate case deliberately.
- Log the exception message, not only a friendly page.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- ShopGoAn e-commerce aggregator with a Python scraping engine behind its catalog, past 10K Google Play downloads.
Related fixes
Back end
CodeIgniter 4 where() builds a different condition than you meant
A SQL syntax error that appears only when a value contains a quote character
The query builder joins every where() with AND and every orWhere() with OR, with no brackets.
3 causes, each with a fixBack end
Call to undefined function mysql_pconnect() after a PHP upgrade
Call to undefined function mysql_connect()
The old mysql_* functions belonged to the ext/mysql extension, which PHP removed in version 7.0.
2 causes, each with a fixBack end
CodeIgniter cannot connect to the MySQL database server
Unable to connect to your database server using the provided settings.
CodeIgniter only reports that its connection failed.
4 causes, each with a fixBack end
Laravel insert fails with 'Field user_id doesn't have a default value'
The insert works when the column is removed or made nullable
Error 1364 means Laravel sent an INSERT without a value for a NOT NULL column that has no default, and MySQL strict mode refuses it.
3 causes, each with a fixBack end
Laravel migration cannot drop a column that has a foreign key
Error on rename of '%s' to '%s' (errno: %d - %s)
MySQL refuses to drop a column while a foreign key constraint still uses it.
2 causes, each with a fixBack end
Laravel: distinct() and count() give the total instead of the unique count
select('city')->distinct()->count() ignores the select
Laravel builds the count from the column you pass to count(), not from select().
2 causes, each with a fix