I\'m trying to build a REST api using Laravel Framework, I want a way to force the API to always responed with JSON not by doing this manulaly like:
return Respo
I've used several mixed solutions also mentioned here to solve everything a bit more dynamic. The reason was here to always reply on every request below "/api" with a json response.
app/Http/Middleware/ForceJsonResponse.php
headers->set('Accept', 'application/json');
return $next($request);
}
}
app/Http/Kernel.php
protected $middlewareGroups = [
...
'api' => [
\App\Http\Middleware\ForceJsonResponse::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
...
];
app/Exceptions/Handler.php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
+ use Throwable;
class Handler extends ExceptionHandler
{
...
+ /**
+ * Render an exception into an HTTP response.
+ *
+ * @param \Illuminate\Http\Request $request
+ * @param \Throwable $e
+ * @return \Illuminate\Http\Response
+ */
+ public function render($request, Throwable $e)
+ {
+ // Force to application/json rendering on API calls
+ if ($request->is('api*')) {
+ // set Accept request header to application/json
+ $request->headers->set('Accept', 'application/json');
+ }
+
+ // Default to the parent class' implementation of handler
+ return parent::render($request, $e);
+ }
}