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']);
>Solution :
This should work:
use Illuminate\Support\Facades\Validator;
$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);
}