'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



Solution 1:[1]

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 App\Http\Middleware;

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' => \App\Http\Middleware\ForceJsonResponse::class,
  //other midlewares
];

protected $middlewareGroups = [
  'api' => [
    //other midlewares
    'json'
    //other midlewares
  ]
];

Solution 2:[2]

I added Accept: application/json on postman and it worked enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 matiaslauriti
Solution 2 ojoago