Skip to content
Advertisement

Laravel validate() method returns index html page when false

I’m building my first laravel API and when I try to validate some mock form data using Postman with POST method, the application returns to me the HTML of the index page and status 200.
Here is my code

 public function store(Request $request)
{
    $request->validate([
       'name' => 'required',
       'slug' => 'required',
       'price' => 'required'
    ]);

    return Product::create($request->all());
}

The application returns the object that was inserted in the database if the validation was successful (if the data was filled in), but returns a HTML file otherwise.

How can I change the way the method ‘validate()’ operates? I’m guessing it is just returning the user to the main page if the form data was not filled correctly

I am using Laravel 8

Advertisement

Answer

You must add Accept: application/json header to your Postman request, without this Laravel works as HTML.

But, in my opinion, all requests in an API must be forced to json response. For this, create app/Http/Middleware/ForceJsonResponse.php

namespace AppHttpMiddleware;

use Closure;

class ForceJsonResponse
{
    public function handle($request, Closure $next)
    {
        if (!$request->headers->has('Accept')) {
            $request->headers->set('Accept', 'application/json');
        }

        return $next($request);
    }
}

And add it to app/Http/Kernel.php

protected $routeMiddleware = [
  //other midlewares
  'json' => AppHttpMiddlewareForceJsonResponse::class,
  //other midlewares
];

protected $middlewareGroups = [
  'api' => [
    //other midlewares
    'json'
    //other midlewares
  ]
];
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement