Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel 10 Form validate rules redirect to home

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

postman output

curl output

>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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading