Ad

Change Password Keeps Redirecting To Same Page

- 1 answer

I am having a hard time debugging this code. I am just new to laravel and i don't know why this code keeps redirecting to the same page even if I used the correct methods. I am using the default authentication of laravel. I don't know if I'm missing something. Here's the code. Thanks!

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class ChangePasswordController extends Controller
{
    public function index(){
        return view('Auth.passwords.changepassword');
    }

    public function changepassword(Request $request){
        $this->validate($request, [
            'oldpassword' => 'required',
            'password' => 'required|confirmed'
        ]);

        $hashedPassword = Auth::user()->password;
        if(Hash::check($request->oldpassword, $hashedPassword)) {
            $user = User::find(Auth::id());
            $user->password = Hash::make($request->password);
            $user->save();
            Auth::logout();
            return redirect()->route('login')->with('successMsg', "Password successfully changed");
        }else{
            return redirect()->back()->with('errorMsg', "Old Password is invalid");
        }
    }
}
Ad

Answer

try this code

   $this->validate($request, [
        'current_password'          => 'required',
        'password'              => 'required|min:6',
        'password_confirmation' => 'required|same:password'
    ]);


   $current_password = $request->current_password;

   $user = auth()->user();

   if (Hash::check($current_password, $user->password)) { 

       $user->fill([
        'password' => Hash::make($request->password)
        ])->save();

        return  redirect()->back()->with('success', 'Password Updated');
   } else{

       return redirect()->back()->with('error', 'Sorry a problem occurred while Updating this Password.');
   }
Ad
source: stackoverflow.com
Ad