JSON Parse Error in Laravel API - How to Fix
This error occurs when Laravel receives invalid JSON in a request body or returns malformed JSON responses.
The Error
JSON parse error / Unexpected token
Common Causes
- 1 Invalid JSON syntax in request body
- 2 PHP errors/warnings output before JSON response
- 3 Debug output breaking JSON
- 4 Missing Content-Type header
- 5 BOM characters in JSON files
Solutions
Ensure proper JSON request format
// Frontend request with correct headers
fetch('/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({ name: 'John' })
});
Disable debug in production
# In .env for production
APP_DEBUG=false
APP_ENV=production
Return proper JSON responses
// Always return JSON from API routes
return response()->json([
'success' => true,
'data' => $data,
'message' => 'Operation successful'
], 200);
// For errors
return response()->json([
'success' => false,
'message' => 'Something went wrong'
], 500);
Validate incoming JSON
// In middleware or controller
$content = $request->getContent();
$data = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return response()->json([
'error' => 'Invalid JSON: ' . json_last_error_msg()
], 400);
}
Need Help With Your Laravel Project?
I specialize in building custom Laravel applications, process automation, and SaaS development. Whether you need to eliminate repetitive tasks or build something from scratch, let's discuss your project.
Currently available for 2-3 new projects
About Hafiz
Full Stack Developer from Italy. I build web applications with Laravel and Vue.js, and automate business processes. Creator of ReplyGenius, StudyLab, and other SaaS products.
View PortfolioRelated Errors
CORS Error in Laravel - How to Fix Cross-Origin Issues
CORS error / Access-Control-Allow-Origin...
ValidationException in Laravel - Handling Validation Errors
The given data was invalid - ValidationE...
429 Too Many Requests in Laravel - Rate Limiting Fix
429 Too Many Requests / Rate limit excee...