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']);
2
Answers
This should work:
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.
Or try including this header in your request.
Otherwise, IlluminateSupportFacadesValidator, faced just do fine.
Reference