Skip to content
Advertisement

Avoid Laravel redirect after validation

I’m making a simple validation on my Laravel controller:

public function updateInfo(Request $request) {

        $validator = $request->validate([
            "name" => ["string", "nullable"],
            "email" => ["email", "nullable"],
            "currentPassword" => ["password:api"]
        ]);

        return json_encode($validator);
}

My problem is that this validation redirects me to the home if fails, and i’m making the request via AJAX, i know that Laravel detects when a request is via Ajax, but it only works if is a normal request (the typical request in which i send the headers with Content Type application/json and in the body i sent a normal JSON

But Laravel is not able of detect when te Ajax request is not of Content Type application/json, i’m using the FormData() object of JavaScript, so, i don’t sent the header Content Type application/json, and in the body i sent the FormData object.

I think it’s simulate a typical HTTP request reloading the page, and for that reason Laravel is not able of detect it, but it gives me troubles with the ajax response because Laravel response the redirect and in my Ajax response i’m catching the HTML Code of the home page.

What can i do?

Advertisement

Answer

You can use validator() helper function with validate() method it will help you with both AJAX calls and normal calls

validator($request->all(), [
    "name" => ["string", "nullable"],
    "email" => ["email", "nullable"],
    "currentPassword" => ["password:api"]
])->validate();
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement