Share icon

In this page you can see how you can update the password of any user in drupal 8 programmatically

There are several case in which you don't have the database access and also if you don't have email service working on drupal 8 website and if you want to reset the password and then this approach will help.

I assume you know how to create basic custom module in drupal 8. Here I am creating a controller class and write code in public function to execute the code using path.

Firstly Create the routing file and give a path like below:

reset_password_by_code.landing:
  path: 'reset-password-by-code'
  defaults:
    _controller: '\Drupal\reset_password_by_code\Controller\CodeResetPassword::content'
    _title: Reset Password By code
  requirements:
   _permission: 'access content'

And then create controller under src/Controller

<?php

namespace Drupal\reset_password_by_code\Controller;
use Drupal\Core\Controller\ControllerBase;


class CodeResetPassword extends ControllerBase{
    public function content(){
        $id = 13;
        
        $user_object = \Drupal::entityManager()->getStorage('user');

        $user = $user_object->load($id);

        $user->setPassword('Ranjanreset24');

        $user->save();
        return array('#markup' => "password updated");
    }
}

After clear cachem when you load path "http://your-domain.com/reset-password-by-code" and where $id you set the password will updated.

you can use this script to update the password in bulk also, for better explanation kindly refer the github module using below link:

https://github.com/key2goal/drupal8-reset-password-programmatically

Hope this helps

Happy Searching, Happy Learning

Add new comment

Restricted HTML