Skip to content

Feature Request: Built-in JSON Response Handling for Validation Errors in API Projects #57086

@abdulaziz1999

Description

@abdulaziz1999

Laravel Version

12

PHP Version

8.4

Database Driver & Version

Mysql 8

Description

Description
Currently, when using Laravel for API development, the framework doesn't automatically return JSON responses for validation errors when using $request->validate(). Developers need to create middleware like ForceJsonResponse to set the Accept header to application/json manually.

This creates additional overhead and is not intuitive for developers building API-focused applications with Laravel.

Problem Example
Without custom middleware, validation errors return HTML responses instead of JSON:

php
// In controller
public function store(Request $request)
{
    $validated = $request->validate([
        'email' => 'required|email',
        'password' => 'required|min:8',
    ]);
    
    // ... logic
}

When validation fails, API clients receive HTML instead of JSON, breaking the expected API response format.

Steps To Reproduce

Current Workaround
Developers must create custom middleware:

php
class ForceJsonResponse
{
    public function handle($request, Closure $next)
    {
        $request->headers->set('Accept', 'application/json');
        return $next($request);
    }
}

Proposed Solution
Automatic JSON Detection: Laravel could automatically detect API requests (based on route prefixes, Accept headers, or config setting)

Configuration Option: Add config/app.php option like 'force_json_for_api' => true

Route-based Detection: Automatically apply JSON responses for routes in api.php

Middleware Package: Include optional built-in middleware for this purpose

Benefits
Better developer experience for API projects

Consistent response format out-of-the-box

Reduced boilerplate code

Standardized API behavior

Similar Implementations
Other frameworks like Symfony and Express.js handle this more elegantly

Laravel Sanctum/Sail already provide API-specific tooling

Additional Context
This would be especially valuable given Laravel's growing popularity as an API backend for:

Mobile applications

SPAs (Vue/React)

Microservices architectures

Third-party integrations

Tags: feature-request, api, validation, json-response

Priority: Medium-High (improves developer experience for API projects)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions