Change user password from tinker in Laravel using artisan command

0
20448
Laravel Framework
Laravel Framework

Through artisan, developers can control almost everything running inside Laravel framework, and it can be a handy tool for updating user password quick and easy.

First, get access to the tinker tool via artisan by issuing the command:


$ php artisan tinker

As you know, Laravel always encrypts user password, so we need to update user password with a hashed one. In order to hash a password, we can use either Hash facade or bcrypt() function.

Let’s try it by hashing a new password value inside tinker.


>>> Hash::make('new_password');
=> "$2y$10$mxpQR9NLHLqTnC0D8I0dmeQcXgwBNULhKOdSZ0otDBI9Uofp9OCaG"
>>> bcrypt('new_password');
=> "$2y$10$3m2RMIAV6xpoqBztNnTOGOHEDKlSrjUIBTY2n5LrzFa7s.BTZqoP."

Each time hashing, we will get a new value, that’s how security works. Okay, so we apply this to current user in system to change his account password. Assuming, we are using `App\User` Eloquent model to map user data, so make the query to appropriate user.


>>> $user = \App\User::first();
=> App\User {#696
     id: 1,
     name: "Pete Houston",
     email: "contact@petehouston.com",
     created_at: "2017-08-22 12:29:48",
     updated_at: "2017-08-22 12:30:55",
   }
>>>

Since we’re inside tinker tool, so we need to provide fully-qualified class name \App\User. After having an User instance, we can change its password by following actions:


>>> $user->password = bcrypt('new_password');
=> "$2y$10$g8uQIe5xDIfT9Zh4wLppVe8UKekPfjwLuDYHfoS2x.HZzAvAQQf8y"
>>> $user->save();
=> true

Make sure to call the save() method on instance in order to persist updated password to database. So user password has been changed successfully!

Beside updating user account, you can do more tasks inside tinker. Anything that is available in Laravel application, it will be available inside tinker tool.