Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation error not returning as json response

When trying to catch my Laravel validation errors using javascript, it keeps giving me the data in html format rather than json format, my validation looks normal. note i am using vue.js 3 and if the validation passes the actual method in the controller works fine, this is just a validation catching issue.

$request->validate([
       'first_name' => ['required', 'string', 'min:3', 'max:255'],
       'last_name' => ['required', 'string', 'min:3', 'max:255'],
       'email' => ['required', 'email', 'min:3', 'max:255'],
       'message' => ['required', 'string', 'min:3']
   ]);

my fetch method is as follows:

fetch('/contact-us', {
            method: 'POST',
            headers: {
                'CONTENT-TYPE': 'application/json'
            },
            body: JSON.stringify(this.form)
        }).then((response) => response.text())
            .then((data) => {
                console.log(data);
                //data = JSON.parse(data);
            }).catch(function(error) {
            console.log('Error: ' + error);
        });

my web route is:

Route::post('/contact-us', [IndexController::class, 'contactForm']);

the error in html format is:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<link href="/css/app.css" rel="stylesheet" />
<script src="/js/app.js" defer></script>
</head>
<body>
<style>
body{
    margin: 0 !important;
    overflow-x: hidden;
}
.container {
    padding-top: 20px;
}
</style>
<div id="app" data-page="{&quot;component&quot;:&quot;ContactUs&quot;,&quot;props&quot;:{&quot;errors&quot;:{&quot;email&quot;:&quot;The email must be a valid email address.&quot;},&quot;csrf&quot;:&quot;tFYwkcZZhNfeb2WXDwdnSv4dchujDvSvLfFGhHW1&quot;},&quot;url&quot;:&quot;\/contact-us&quot;,&quot;version&quot;:&quot;0f4e2ee0f7e2ca9da665d2f8035743df&quot;}"></div></body>
like image 877
sgb999 Avatar asked Oct 27 '25 19:10

sgb999


1 Answers

If you specify the Accept:application/json header in request, laravel will return json response

like image 107
Ilya webdev Avatar answered Oct 29 '25 08:10

Ilya webdev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!