Api Laravel 8 Laravel 9 Laravel 10 Laravel 11 Laravel 12

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

Error Message
JSON parse error / Unexpected token

Common Causes

  1. 1 Invalid JSON syntax in request body
  2. 2 PHP errors/warnings output before JSON response
  3. 3 Debug output breaking JSON
  4. 4 Missing Content-Type header
  5. 5 BOM characters in JSON files

Solutions

1

Ensure proper JSON request format

JavaScript
// Frontend request with correct headers
fetch('/api/data', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    },
    body: JSON.stringify({ name: 'John' })
});
2

Disable debug in production

ENV
# In .env for production
APP_DEBUG=false
APP_ENV=production
3

Return proper JSON responses

PHP
// 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);
4

Validate incoming JSON

PHP
// 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

Hafiz Riaz

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 Portfolio

Related Errors