How to change user password in laravel ?

Laravel authentication scaffolding provides easy way for user registration, login/logout and password reset. Builtin structure uses traits like RegistersUsers, ResetsPasswords, AuthenticatesUsers and SendsPasswordResetEmails for authentication functionalities. These traits are easily customizable which makes easy way for customizing authentication process. However, user password change is still missing in the above structure.

After running php artisan make:auth, views controller and routes are created so that, we can register user to the system, We can perform login, logout and password reset actions. Now, we will create structures for the password change functionality.

See more about authentication in official documentation

Step I Create Password Change form

We need following fields for the password reset form.

  • Current Password

  • New Password

  • Confirm Password

Also Read: Using View Composer In Laravel

We already have our app.blade.php layout. We will extend this layout to create following password change form.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <h4>Change Password</h4>
        <div class="col-md-12">
            @if (session('status'))
                <p class="alert alert-success">{{ session('status') }} <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a></p>
            @endif
            @foreach (['danger', 'warning', 'success', 'info'] as $msg)
                @if(Session::has('alert-' . $msg))
                    <p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a></p>
                @endif
            @endforeach
            <form class="form-horizontal" method="POST" action="{{url('password/change')}}">
                {{ csrf_field() }}
                
                <div class="form-group">
                    <label for="current_password">Current Password</label>
                    <input id="current_password" type="password" class="form-control" name="current_password" required placeholder="Enter Password">
                    @if ($errors->has('current_password'))
                        <span class="help-block">
                            <strong>{{ $errors->first('password') }}</strong>
                        </span>
                    @endif
                </div>

                <div class="form-group">
                    <label for="password">Password</label>
                    <input id="password" type="password" class="form-control" name="password" required placeholder="Enter at least 6 Character">
                    @if ($errors->has('password'))
                        <span class="help-block">
                            <strong>{{ $errors->first('password') }}</strong>
                        </span>
                    @endif
                </div>

                <div class="form-group">
                    <label for="password-confirm">Confirm Password</label>
                    <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required placeholder="Confirm Password">
                    @if ($errors->has('password_confirmation'))
                        <span class="help-block">
                            <strong>{{ $errors->first('password_confirmation') }}</strong>
                        </span>
                    @endif
                </div>

                <div class="form-group">
                    <div class="col-12 text-center">
                        <button class="btn btn-primary" type="submit">Submit</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection


Here, User have to enter old password to create new password. Now, we will define two routes, a get route to display a form and a post route to update password.

Adding password change routes

 

// Password Change Routes...

Route::get('password/change', 'Auth\AuthController@changePassword');

Route::post('password/change', 'Auth\AuthController@postChangePassword');

Now, we will create AuthController and corresponding functions.

php artisan make:controller Auth\AuthController

Above command will create AuthController.php file inside app/Http/Controllers/Auth/ Directory.

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
    //
}

Only logged in users should able to change password so, we have to add middleware for the AuthController.

<?php 

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
    public function __construct()
    {
	    $this->middleware('auth');
    }
}

In order to validate the form request sent from view, we will create a request class with following artisan command.

php artisan make:request ChangePasswordRequest

Above command will create a request class inside app/Http/Requests/ directory where we will add rules and error messages for form request validation.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ChangePasswordRequest 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 [
            'password' => 'required|same:password',
            'password_confirmation' => 'required|same:password',
            'current_password' => 'required'
        ];
    }

    /**
     * Get the validation error messages that apply to the request.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'password.required' => 'Password field is required',
            'password_confirmation.required' => 'Password confirmation field is required',
            'password_confirmation.same' => 'Field should be same as New Password',
            'current_password.required' => 'Current password field is required'
        ];
    }
}

Here, New password and password confirmation field are required and should be same. In order to make more secure password change process, We have added current password field in the form.

Also Read: How to use AJAX with Laravel and jQuery ?

Now, we will use this request class to validate request in the controller. We will add logic to update the password in AuthController like this:

<?php

namespace App\Http\Controllers\Auth;

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

use App\User;
use App\Http\Requests\ChangePasswordRequest;

class AuthController extends Controller
{
    public function __construct()
    {
	    $this->middleware('auth');
    }

    public function changePassword()
    {
        return view('auth.passwords.change')->with(
            ['email' => Auth::user()->email]
        );
    }

    public function postChangePassword(ChangePasswordRequest $request)
    {
    	if(Auth::Check())
  	    {	 
            if(\Hash::check($request->current_password,Auth::User()->password))
               {
    			$user = User::find(Auth::user()->id)->update(["password"=> bcrypt($request->password)]);    	
  			}
  			else{
  				return redirect()->back()->with('alert-danger','Incorrect Details !');
  			}
  		}
        return redirect()->to('/')->with('alert-success','Password changed successfully !');
    }
}

Here, Change password function returns a view to display password change form. When user fills all the field and submits the details, request will arrive at postChangePassword function through route. At first, validation is performed with set of rules defined in ChangePasswordRequest class and then controller code will be executed.

Auth::check() will check for logged in user and Hash::check() function is used to current password is correct or not. After that we update the user password using eloquent model.


share :

Sagar Gautam

A Computer Engineer from Nepal.


Leave your Feedback