Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Force Json Response Laravel Package

bibrokhim/laravel-force-json-response

Laravel middleware that forces every request to accept JSON by setting the Accept header to application/json when missing or different, ensuring your app consistently returns JSON responses. Install via composer require bibrokhim/laravel-force-json-response.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bibrokhim/laravel-force-json-response
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Bibrokhim\ForceJsonResponse\ForceJsonResponseServiceProvider"
    
  2. Enable the Package: Add the middleware to your HTTP kernel (app/Http/Kernel.php):

    protected $middleware = [
        // ...
        \Bibrokhim\ForceJsonResponse\Middleware\ForceJsonResponse::class,
    ];
    
  3. First Use Case: Immediately, all HTTP responses (except those explicitly returning JSON) will be converted to JSON format. Test by making a request to any route—non-JSON responses (e.g., HTML, plain text) will now return as JSON with a data key:

    {
        "data": "Your response content"
    }
    

Implementation Patterns

Core Workflow

  • API-Only Projects: Ideal for headless APIs where clients expect JSON. Eliminates manual Response::json() calls for non-JSON responses.
  • Hybrid Apps: Useful for APIs embedded in SPAs or mobile apps where consistency is critical.

Integration Tips

  1. Exclude Routes: Override the config (config/force-json-response.php) to exclude specific routes or middleware groups:

    'except' => [
        'web', // Exclude web middleware group
        'admin/*', // Exclude admin routes
    ],
    
  2. Conditional JSON: Temporarily disable JSON forcing for specific routes by wrapping logic in middleware:

    public function handle($request, Closure $next) {
        $response = $next($request);
        return $this->shouldForceJson($request) ? $response : $response->setContent(json_encode($response->getContent()));
    }
    
  3. Custom JSON Structure: Extend the middleware to modify the JSON wrapper:

    // app/Http/Middleware/ForceJsonResponse.php
    public function handle($request, Closure $next) {
        $response = $next($request);
        return response()->json(['custom_key' => $response->getContent()]);
    }
    
  4. Testing: Mock the middleware in tests to verify JSON responses:

    $response = $this->withMiddleware(\Bibrokhim\ForceJsonResponse\Middleware\ForceJsonResponse::class)
                     ->get('/api/endpoint');
    $response->assertJsonStructure(['data']);
    

Gotchas and Tips

Pitfalls

  1. Unexpected HTML Responses: If your app serves HTML (e.g., Blade templates), ensure routes are excluded to avoid breaking frontend rendering. Example:

    'except' => ['web', 'sanctum/csrf-cookie'], // Exclude web and CSRF routes
    
  2. File Downloads: Binary responses (e.g., PDFs, images) may be incorrectly wrapped in JSON. Exclude these routes or handle them separately:

    if ($request->is('downloads/*')) {
        return $next($request);
    }
    
  3. Caching Headers: JSON-wrapped responses may interfere with caching logic (e.g., Cache-Control). Verify headers in responses:

    $response->header('Cache-Control', 'public, max-age=3600');
    

Debugging

  • Check Middleware Order: Ensure ForceJsonResponse runs after TrimStrings, ConvertEmptyStringsToNull, and before ConvertEmptyStringsToNull if you rely on these for data normalization.

  • Log Excluded Routes: Temporarily log excluded routes to debug misconfigurations:

    \Log::debug('Excluded route:', [$request->path()]);
    

Extension Points

  1. Custom JSON Wrapper: Override the wrapJson() method in the middleware to customize the response structure:

    protected function wrapJson($content) {
        return response()->json(['meta' => ['status' => 'success'], 'data' => $content]);
    }
    
  2. Dynamic Exclusions: Use route middleware to conditionally exclude JSON forcing:

    // Route
    Route::get('/dynamic', function () {
        // ...
    })->middleware('throttle:10,1')->middleware('json:exclude');
    
  3. Performance: For high-traffic APIs, benchmark the overhead of JSON wrapping. Consider caching responses to mitigate impact.

  4. Fallback for Non-JSON Clients: Add logic to detect client expectations (e.g., Accept: text/html) and bypass JSON forcing:

    if ($request->wantsJson() === false) {
        return $next($request);
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope