Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mimo's avatar
Level 1

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.

0 likes
4 replies
CodeNathan's avatar

@mimo Add this method to your FormRequest class ;)

    public function wantsJson()
    {
        return true;
    }
mimo's avatar
Level 1

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);
        }
}

But the header is not set :(

When I set

$request->headers->add(['X-Requested-With' => 'XMLHttpRequest']);
dd($request->ajax());
return $next($request);

It returns true, but still thinks it's not a json call. Maybe the request is analysed before the middleware is manipulating the header.

CodeNathan's avatar

Just change the add to set


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);
        }
}


mimo's avatar
Level 1

@CodeNathan: add is calling set, so there is no difference.

I endend up with a new request class for all.

class JsonRequest extends FormRequest
{
        public function expectsJson()
        {
            return ($this->route()->getAction()['middleware'] == 'api');
        }
}

Now I have to edit all classes that a generated by the cli, but this works like I want :)

Please or to participate in this conversation.