skip to Main Content

I have been working on a Laravel API project and created this controller function to register the API route. If I remove the validator, it works fine meaning it doesn’t take me to the Laravel homepage when I send a POST request

But I can’t leave it without validation so when I am trying to send a blank request to check if the validator is working or not it takes me to the homepage ( screenshot added of Postman check below and cURL )

public function register(Request $request)
    {

        $validatedData = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|unique:users|max:255',
            'password'  => 'required|min:6',
        ]);

        if ($validatedData->fails()) {
            return response()->json(['message' => $validatedData->messages()], 422);
        }

        $user = new User();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = Hash::make($request->password);
        $user->role = 0;
        $user->save();
        
        return response()->json(['message' => 'Patient registered successfully'], 201);

    }

and my API route is:

Route::post('patient/register', [PatientController::class, 'register']);

postman output

curl output

2

Answers


  1. This should work:

    use IlluminateSupportFacadesValidator;
    
    $validator = Validator::make($request->all(), [
        'name' => 'required|max:255',
        'email' => 'required|unique:users|max:255',
        'password' => 'required|min:6',
    ]);
    
    if ($validator->fails()) {
        return response()->json(['message' => $validator->errors()], 422);
    }
    
    Login or Signup to reply.
  2. You can try either two ways if you want to validate with $request->validate().
    The default behavior of $request->validate() is to return to previous web route with error bags.

    Try it in try-catch block and manually returning errors, it will get automatically converted to JSON response.

    try{
    
       $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|unique:users|max:255',
            'password'  => 'required|min:6',
        ]);
    
     catch(IlluminateValidationValidationException $ex){
         return $ex->validator->errors();
    }
    

    Or try including this header in your request.

    Accept: application/json
    

    Otherwise, IlluminateSupportFacadesValidator, faced just do fine.

    Reference

    Laravel validation error not returning as json response

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search