Home » Php » How does the static password work in the default Laravel user factory?

How does the static password work in the default Laravel user factory?

Posted by: admin November 30, 2017 Leave a comment


Per this link, https://laravel.com/docs/5.4/database-testing#writing-factories, the default Laravel user factory tests the value of a static $password variable. If it is falsey, it bcrypts ‘secret’ and uses that.

How does one go about setting the value of the static variable $password? Obviously I don’t want to import it at the time the function is declared (since that would defeat the purpose of making it variable). I realise that I can override the value of password by passing an array to the make() method, but this is a different thing altogether.


I had the exact same question and found the answer here:

See the comment at the bottom

bcrypt() is an expensive call, which is part of its advantage as a password hashing algorithm.
Since the fake password being generated is hardcoded to ‘secret’, there is no need to bcrypt() the password every time.
By using a static variable, we can bcrypt() the password once, and then use that same hash value on every subsequent call to the factory (within the same request).
So, for example, imagine you were setting up a test that needed 100 users.
$users = factory(User::class, 100)->create();
That code will call the factory closure 100 times. Without the static $password variable, bcrypt() would run 100 times, which could take a couple seconds. With the static variable, bcrypt() now only runs once, and the result is used for all 100 users, which greatly increases the speed of your test.

So the static $password is not for including some password from the outside. It is just a clever trick to gain performance.