skip to Main Content

I’m working on a Laravel project, and I’ve created a password change API. Here’s the route I’m using:

Route::post('/change-password', function (Request $request) {
    // Validate the request data
    $request->validate([
        'current_password' => 'required|string',
        'new_password' => 'required|string|confirmed|min:8',
    ]);

    // Check if the current password matches the user's current password
    if (!Hash::check($request->current_password, $request->user()->password)) {
        return response()->json([
            'message' => 'The provided current password does not match your current password.',
        ], 422);
    }

    // Update the user's password
    $request->user()->password = bcrypt($request->new_password);
    $request->user()->save();

    return response()->json([
        'message' => 'Password has been changed successfully.',
    ], 200);
})->middleware('auth:sanctum')->name('password.change');

When I test this I get status code 200 but, password is not changed.
[I am not looking for reset password, I am looking for change password for authenticated user.]

I tried : user()->updated(), AI chatbot.

2

Answers


  1. Update your code like below

    use IlluminateHttpRequest;
    use IlluminateSupportFacadesHash;
    
    Route::post('/change-password', function (Request $request) {
        $validated = $request->validate([
            'current_password' => 'required|current_password',
            'new_password' => 'required|confirmed|min:8',
        ]);
    
        $request->user()->update([
            'password' => Hash::make($validated['password']),
        ]);
    
        return response()->json([
            'message' => 'Password has been changed successfully.',
        ], 200);
    })->middleware('auth:sanctum')->name('password.change');
    
    Login or Signup to reply.
  2. Have you tried:

    $user = $request->user();
    $user->name = 'blah blah'; //for debug purpose
    $user->password = bcrypt('password');
    $user->save();
    
    dd($user->refresh);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search