Use always JSON for error responses for /api/* calls
Hello everyone,
I am building an API and want to use the FormRequest class. All api calls for api/* should return json objects. When I send Accept: application/json in the header I get the result. But is it possible to write some Middleware that is bind to api to set this header?
Another approach would be to modify the FormRequestclass, but then I can't divide the routes anymore.
But then all requests, even the one who goes to web. will be json.
I thought a middleware could help:
namespace App\Http\Middleware;
use Closure;
class Json
{
/**
* Modifies the Accept header so the result is always printed in json.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$request->headers->add(['Accept' => 'application/json']);
return $next($request);
}
}
namespace App\Http\Middleware;
use Closure;
class Json
{
/**
* Modifies the Accept header so the result is always printed in json.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
return $next($request);
}
}