Data Truncation
The data being inserted or updated is too long for the column's defined size.
Explanation
Data truncation occurs when you try to insert or update data that exceeds the maximum allowed length for a column. For example, inserting a 300-character string into a VARCHAR(255) column. MySQL by default issues a warning and truncates the data, but with strict mode enabled (which is the default in modern MySQL), it throws an error instead. This can cause unexpected failures, especially when working with user input that hasn't been validated.
Common Causes
- Data exceeds column length limit
- Column defined too small for use case
- Binary data in text column
- Unicode characters counting differently
- Strict mode enabled rejecting truncation
Solution
Validate data length before inserting or updating. Check the column definition to understand size limits: DESCRIBE table_name. Use validation rules in Laravel: 'max:255' for strings. Increase column size via migration if the data legitimately needs more space. Use TEXT or MEDIUMTEXT for larger text content. Disable strict mode only as a last resort (not recommended). Handle the exception gracefully and provide user-friendly error messages.
Code Example
// This fails if name exceeds VARCHAR(255)
User::create([
'name' => str_repeat('A', 300), // too long!
'email' => 'test@example.com'
]);
// Fix: validate input length
$request->validate([
'name' => 'required|string|max:255',
]);
// Check column size
// MySQL: DESCRIBE users;
// PostgreSQL: \d users
// Increase column size via migration
Schema::table('users', function (Blueprint $table) {
$table->string('name', 500)->change(); // increase to 500
});
// For large text, use TEXT type
Schema::table('users', function (Blueprint $table) {
$table->text('bio')->change(); // unlimited text
});
// Handle truncation gracefully
try {
User::create($data);
} catch (QueryException $e) {
if (Str::contains($e->getMessage(), 'Data truncation')) {
return response()->json(['error' => 'Input too long'], 422);
}
throw $e;
}
Error Information
Language
php
Framework
laravel
Difficulty
Beginner
Views
14
Related Errors
PHP
Headers Already Sent
The code tries to send HTTP headers after output has already been sent to the browser.
429
Backend
Rate Limit Exceeded (429)
Too many requests were sent in a given amount of time.
DevOps
Laravel Schedule Task Failure
A scheduled task failed to execute or completed with errors.
404
Laravel
ModelNotFoundException (404)
Thrown when a requested model instance cannot be found in the database.