Amin khalaf
Amin khalaf

Reputation: 15

Checking old password with password column in database

I need to check the password given by the user in an input and check it. If it's right I'll update the password with new password, if the password is wrong I want to give the user an alert in laravel 5.4.

controller:

public function edit(Request $request){

    $user = new User;
    $user = $user->find(1);

            $oldpassword = $request->input('oldpassword');
            $newpassword = $request->input('newpassword');

        //if condition 
        /*if (user()->id == $oldpassword){
            $updatesucess = 1;
        }else {
            $updatesucess = 0;
        }*/


            $user->update(['password' => $newpassword]);
            return back();
        }

view:

@section('content')
<div class="form">
    <div class="logo-area">
        <img src="images/logo.png">
    </div>
    <form method="POST" action="/edit">
     {{ csrf_field() }}
        <input type="password" name="oldpassword" placeholder="old Password" required>
        <input type="password" name="newpassword" placeholder="new Password" required>
        <input type="submit" value="Save changes">
    </form>

Upvotes: 1

Views: 2135

Answers (2)

Wakil Ahmed
Wakil Ahmed

Reputation: 1393

For Laravel versions>8 this is the best solution.

'old_password' => 'required|current_password'

You can also specify the api

'old_password' => 'required|current_password:web'

Upvotes: 0

Seva Kalashnikov
Seva Kalashnikov

Reputation: 4392

Use check method of Hash facade (documentation)

  1. In your controller file add Hash facade:

    use Illuminate\Support\Facades\Hash;
    
  2. Add password check and in case of mismatch handle redirect with an error

    $user = User::find(1);
    
    $oldpassword = $request->input('oldpassword');
    
    if (Hash::check($oldpassword, $user->password)) {
      // redirect back with error
    }
    
  3. Update user password using Hash::make

     $newpassword = $request->input('newpassword'); 
     $user->update(['password' => Hash::make($newpassword)]);
    

Upvotes: 1

Related Questions