0

I have a validation in my Laravel 8 API which validates input from camera. Camera can not send any header which will say that it accept application/json. So Laravel send me 302 redirect response on error insted of errors in json. Is there a way how to force Laravel to send json response insted of redirect on validation error? Thanks for help.

Čamo
  • 3,863
  • 13
  • 62
  • 114
  • 1
    Does this answer your question? [How do you force a JSON response on every response in Laravel?](https://stackoverflow.com/questions/36366727/how-do-you-force-a-json-response-on-every-response-in-laravel) – Vincent Decaux Aug 25 '23 at 08:22

1 Answers1

-1

Yes, you can apply a middleware in the route in order to set the header you need.

In order to achive this task you need to create a middleware with this command :php artisan make:middleware SetJsonContentType.

Note: Replace SetJsonContentType with whatever name you likes.

The file will be generated under the app/Http/Middleware directory.

In the handle method of the Middleware you need to insert the following code:


   $request->headers->set('Accept', 'application/json');
   return $next($request);

after this, you need to use the middleware in the request. To do so, you need to add the middleware SetJsonContentType to the web section of the app/Http/Kernel.php file. You will end with something like this:


protected $middlewareGroups = [
    'api' => [
        \App\Http\Middleware\SetJsonHeader::class,
       //other middlewares
    ],

    'web' => [
        // ...
    ],
];

I hope that this colud help you.

JDarwind
  • 97
  • 6