Search code examples
phplaravelvalidationlaravel-validation

Laravel Validator Not Working Properly - Redirecting main page


Laravel 5.5

public function register(Request $request) {
    request()->validate([
        'email' => 'required:email'
        'password' => 'required|min:6'
    ]);

    return response()->json(["message" => "Hello World"]); 
}

If validator is fails, not giving error messages. Redirecting main page.


Solution

  • If the code you're using redirects you to the previous page when validation fails, it means that you didn't tell the server what kind of response you want to receive.

    Set a proper header to get JSON. It will make the validator send JSON in response. For example:

    $.ajax({
      headers: {
        Accept : "application/json"
      },
      ...
    });
    

    Then this code will work as expected:

    public function register(Request $request) 
    {
        $request->validate([
            'email' => 'required:email'
            'password' => 'required|min:6'
        ]);
    
        return response()->json(["message" => "Hello World"]);
    }