Last active
July 11, 2022 09:19
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} | |
Hi, thank you so much!
I noticed something. When a NotFoundHttpException happens because of sending a model id that doesn't exist via path parameter, the error is not displayed in JSON (unless you manually add the header). In the next code you can see how I solved it:app/Exceptions/Handler.php
public function render($request, Exception $exception) { if (in_array('api', $request->route()->middleware())) { $request->headers->set('Accept', 'application/json'); } return parent::render($request, $exception); }
When it's a 404 error (route not found) there will be an exception, because $request->route()
will return null.
I just change it a little:
if ($request->route() !== null && in_array('api', $request->route()->middleware())) {
$request->headers->set('Accept', 'application/json');
}
But with this fix you'll get an HTML response as default in case when it's 404 error.
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);
}
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
You can place that middleware wherever you want in your middleware groups, just make sure that it's defined first in the
$middlewarePriority
array.If you cannot see that array in your Http Kernel, copy/paste it from the parent class:
Illuminate\Foundation\Http\Kernel
. (I think it's been removed from 7.x by default).