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

Using View Composer In Laravel

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

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

Now, we will create AuthController and corresponding functions.

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

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

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

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

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.

Using Ajax in Laravel

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:

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.



Computer Enginner, A Laravel Developer,

Leave a Reply

Your email address will not be published. Required fields are marked *