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.
App\Http\Middleware\TrimStrings, ConvertEmptyStringsToNull).return response()->view() in controllers).laravel-debugbar)./dashboard)./health or /admin)?HEAD, OPTIONS)?App\Http\Kernel.php).return view(), return redirect()->back())./login, /admin).composer require bibrokhim/laravel-force-json-response
Publish config (if available) or manually register middleware in Kernel.php:
protected $middleware = [
\Bibrokhim\ForceJsonResponse\Middleware\ForceJsonResponse::class,
// ... other middleware
];
app/Http/Middleware/ForceJsonResponse.php to add route whitelists/blacklists.public function handle($request, Closure $next) {
if ($request->is('admin/*')) return $next($request);
return $next($request)->setEncodingOptions(JSON_UNESCAPED_SLASHES);
}
Content-Type: application/json).Symfony\Component\HttpKernel\Exception\HttpException (e.g., 500 errors from malformed JSON).Illuminate\Http\Resources\JsonResource.App\Exceptions\Handler).$request or $response (e.g., spatie/laravel-activitylog, laravel-debugbar).config/force-json.php) for maintainability.App\Exceptions\Handler returns JSON-compatible exceptions.telescope or laravel-debugbar (if compatible) to inspect failed requests.Cache-Control). Ensure caching middleware (e.g., stripe/laravel-cashier) is compatible.| Failure Scenario | Impact | Mitigation |
|---|---|---|
| Middleware conflicts | Broken responses (500 errors) | Test with all middleware in staging. |
| HTML route not exempted | UI rendering failures | Automate route audits (e.g., php artisan route:list). |
| Third-party package incompatibility | Feature regressions | Test with critical packages pre-deployment. |
| Exception handling issues | Unreadable error responses | Customize App\Exceptions\Handler for JSON. |
| PHP version incompatibility | Installation failures | Pin PHP version in composer.json. |
README.md with:
How can I help you explore Laravel packages today?