Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

639
Views
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

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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
  ]
];
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!