Skip to content

Instantly share code, notes, and snippets.

@meSingh
Last active July 11, 2022 09:19
Show Gist options
  • Save meSingh/c90c5abc81a9cc0687a62a84eb2c696b to your computer and use it in GitHub Desktop.
Save meSingh/c90c5abc81a9cc0687a62a84eb2c696b to your computer and use it in GitHub Desktop.
If you are using laravel as api only, you might want to return JSON on every request, even on errors/exceptions. The easiest way to do so is using this middleware globally.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class JsonMiddleware
{
public function handle(Request $request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
return $next($request);
}
}
@getmanzooronline
Copy link

If you need 404 also in JSON, update the render function as follows. This solved for me in Laravel 6

app/Exceptions/Handler.php

public function render($request, Exception $exception)
{
        if (substr($request->server()['REQUEST_URI'],1,3) =='api') {
            $request->headers->set('Accept', 'application/json');
        }
        return parent::render($request, $exception);
}

@harryqt
Copy link

harryqt commented Jul 11, 2022

Returns "text/html; charset=UTF-8"

Route::get('/foo', function () {
    return 'hello world';
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment