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

when change user password in laravel by using modal, it always return false ajax?

I’m trying to implement (changePassword) method, that enables users to change their old password, I used (modal) and ajax for this like that:

enter image description here

data comes from ajax to (controller) fine, but:

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

  • when I compare (oldPassword) that comes from user (modal), to the (hashed currentPassword) that store in database, always says it’s wrong, although (the oldPassword that comes from modal) the same password that stored in database?

Route:

    Route::group(['middleware'=>'auth:web'], function(){
    Route::get('/profile', [ProfileController::class,'profile'])->name('profile');
    Route::post('/change-password', [ProfileController::class,'changePassword'])->name('profile.changePassword');
});

controller:

    public function changePassword(ProfilePasswordRequest $request)
{
    try{
        $currentPass = Auth::user()->password;
        if (Hash::check($request->oldPassword, $currentPass)) {
            $user = User::find(Auth::id());
            $user -> password = Hash::make($request->password);
            $user -> save();

            return response()->json([
                'status' => true,
                'msg' => 'Your password changed successfully',
            ]);
        }else{
            return response()->json([
                'status' => false,
                'msg' => 'Old password is wrong',
            ]);
        }

    }catch (\Exception $ex){
        return $ex;
        return redirect()->back()->with(['error' => 'Something error please try again later']);
    }
}

always the return response go to (else), although (the oldPassword that comes from modal) the same password that stored in database?

  'status' => false,
  'msg' => 'Old password is wrong',

Chang password request:

    <?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ProfilePasswordRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'oldPassword' => 'required',
            'password' => 'required|confirmed|min:8',
        ];
    }
}

script:

    <script>
    $(document).on('click', '#changePassword', function(e){
        $("#changePassword").attr("disabled", true);
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $('#oldPassword_error').text('');
        $('#password_error').text('');

        var password = $('#password').val();
        var oldPassword = $('#oldPassword').val();
        var passwordConfirmation = $('#password_confirmation').val();
        console.log(oldPassword);

        $.ajax({
            type: 'post',
            url: "{{route('profile.changePassword')}}",
            data:{
                oldPassword:oldPassword,
                password:password,
                password_confirmation:passwordConfirmation
            },
            cache: false,
            success: function (response){

                if(response.status===true){
                    $('#changPassForm')[0].reset();
                    $('#ChangePasswordMsgSucc').show();
                    $("#changePassword").attr("disabled", false);
                }
                if(response.status===false){
                    $('#changPassForm')[0].reset();
                    $('#ChangePasswordMsgError').show();
                    $("#changePassword").attr("disabled", false);
                }

            }, error: function (reject){
                $("#changePassword").attr("disabled", false);
                var response = $.parseJSON(reject.responseText);
                $.each(response.errors, function(key, val){
                    $("#" + key + "_error").text(val[0]);
                });
            }
        });
    });
</script>

bade page:

            <div class="modal fade" id="exampleModal2" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel2" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">

          <div  class="row mr-2 ml-2">
              <button id="ChangePasswordMsgError" style="display: none" type="button" class="btn btn-lg btn-block btn-outline-danger mb-2"
                      >Your old password is wrong
              </button>
          </div>

          <div  class="row mr-2 ml-2">
              <button id="ChangePasswordMsgSucc" style="display: none" type="button" class="btn btn-lg btn-block btn-outline-danger mb-2"
              >Your old password is wrong
              </button>
          </div>

           <div class="row  d-flex justify-content-center " style="font: normal normal bold 24px/45px Cairo; color: #0D67CB">

    <p class="text-center">Change your Password</p>

    </div>
          <form id="changPassForm">
              @csrf
        <div class="row mt-3 pl-3 pr-3 mr-3 ml-3 d-flex justify-content-center">
           <input type="password" id="oldPassword" class="form-control" placeholder="Old Password">
            <small id="oldPassword_error" class="form-text text-danger"></small>
        </div>
        <div class="row mt-3 pl-3 pr-3 mr-3 ml-3 d-flex justify-content-center">
           <input id="password" type="password" class="form-control" placeholder="New Password">
            <small id="password_error" class="form-text text-danger"></small>
        </div>
        <div class="row mt-3 pl-3 pr-3 mr-3 ml-3 d-flex justify-content-center">
           <input id="password_confirmation" type="password" class="form-control" placeholder="Confirm New Password">
        </div>
          </form>

      </div>
      <div class="modal-footer pr-5 pt-5 pb-5">
       <button type="button" class="btn btn-light">Reset</button>
       <button id="changePassword" type="button" class="btn btn-warning">Change</button>

      </div>
    </div>
  </div>
</div>

I tried to console.log() all values that comes from ajax and, it comes successfully.

any help please.

>Solution :

I’m not 100% sure this is the issue, but are the request variables accessible using -> notation. Or do you have to call ->get(‘name’) or ->input(‘name’)

if (Hash::check($request->get('oldPassword'), $currentPass)) {
        $user = User::find(Auth::id());
        $user->password = Hash::make($request->get('password'));
        $user->save();

        return response()->json([
            'status' => true,
            'msg' => 'Your password changed successfully',
        ]);
    } else {
        return response()->json([
            'status' => false,
            'msg' => 'Old password is wrong',
        ]);
    }
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