Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

637
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda