At times, you might want to generate a random password for each user. Very simple! The following is about the simplest function in laravel which is how to generate random password in laravel. Then hash
- First we will see how to generate random string.
- Then how to hash it.
How to generate random string
For this, Laravel has a variety of global “helper” PHP functions. One of these functions are str_random($length)
.
For Example,
$randString = str_random(10);
This will give you a random 10 digit string like the following:
iGed7JqIp0
qXP51g0hYH
QP5b9Z71Kv
Q017CEZmoG
How To Hash
Finally, how can we hash the randomly generated strings. Hashing a string in laravel has been made too easy. Laravel has as secure Bcrypt hashing. It is found in laravel Hash
facade. Here is how to use:
Before all don’t forget to import Hash
use Illuminate\Support\Facades\Hash;
Then hash the randomly generated string like this:
$hashedString = Hash::make($randString);
This will generate something like the following:
$2y$10$mwhKl6Rm61OQxk.7/./UVe0AG91c8cItSxCQ.uKP2TtnJheAj6K9K
$2y$10$7KufR/Ng.RH7OohTgAiqwegQfqtKWqe6ynxZpisGqRdHuLnr8dWaq
$2y$10$AYLeSt6RocMzGovU4bAveeIigZZ0qvQ/lefir.skne1eqdFGz/YBK
As a plus, What if you want to check a string may be a password against a hash. Also this is very simple. Just do it as follows using the check
function:
$result = Hash::check('your string', $hashedString)
The check
function verifies that whether a given string corresponds to a given hash or not.
2 Comments
qptisxbvqn · March 21, 2021 at 6:49 pm
Muchas gracias. ?Como puedo iniciar sesion?
Abdulhakim Zeinu · June 14, 2021 at 2:13 am
¿Iniciar sesión en qué?