Laravel Validator Not Working Properly - Redirecting main page

Viewed 7220

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.

5 Answers

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"]);
}

I had the same problem when testing my rest api in Postman application.

  1. if we don't want to modify our current code of laravel redirect repose, we have to put Accept:-application/json and ContentType:-application/json

enter image description here

  1. For modifying code in controller class file, i did it like this and got the json response instead of redirecting to home page.

       public function register(Request $request)
       {
           $validator = Validator::make($request->all(), [
             'name' => 'required|string|max:255',
             'email' => 'required|string|email|max:255|unique:users',
             'password' => 'required|string|min:6',
             ]);
    
            if ($validator->fails()) {
               return response()->json($validator->errors());
             } else {
                // do something
            }
        }
    

before it looks like below codes it was redirecting to home page

This is validator function

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6',
    ]);
}

public function register(Request $request)
{
   
    // Here the request is validated. The validator method is located
    // inside the RegisterController, and makes sure the name, email
    // password and password_confirmation fields are required.
    $this->validator($request->all())->validate();

    // A Registered event is created and will trigger any relevant
    // observers, such as sending a confirmation email or any 
    // code that needs to be run as soon as the user is created.
    event(new Registered($user = $this->create($request->all())));

    // After the user is created, he's logged in.
    $this->guard()->login($user);

    // And finally this is the hook that we want. If there is no
    // registered() method or it returns null, redirect him to
    // some other URL. In our case, we just need to implement
    // that method to return the correct response.
    return $this->registered($request, $user)
                    ?: redirect($this->redirectPath());
}

You can do this like this :

$validator = Validator::make($request->all(), [
    'email' => 'required|email', //use pipe here to apply multiple validations rules and add a ','
    'password' => 'required|min:6'
]);

if ($validator->fails()) {
    return response()->json(['errors' => $validator->errors()]);
}
return response()->json(["message" => "Hello World"]);

The validation is working well, but, $request->validate() will redirect you to the previous page. I recommend you to manually create your validations: Manually Creating Validations. You could do something like this:

use Illuminate\Http\Request;
use Validator;

class YourClass extends Controller{
    public function yourFunction(Request $request) {
        $validator = Validator::make($request->all(),[
            'field_1' => 'rule1|rule2',
            'field_2' => 'rule1|rule2'
        ]);
        
        if ($validator->fails()) {
            return response()->json($validator->errors());
        } else {
            /*Something else*/
        }
    }
}

try this, hope this code can help you

$this->validate($request, [
        'email'    => 'required|email',
        'password' => 'required|min:6'
    ]);
Related