mstnorris's avatar

hash user password in lumen

I'm just playing around with lumen, how do I go about hashing a user's password?

Using bcrypt in my ModelFactory.php I get the following error when trying to seed the database.

[Symfony\Component\Debug\Exception\FatalThrowableError]
  Fatal error: Call to undefined function bcrypt()

FYI: Lumen (5.2.5) (Laravel Components 5.2.*)

0 likes
9 replies
jekinney's avatar

bcrypt is avalible (matter of fact its core php function).

jekinney's avatar

Wierd, let me look at my code in a bit and see what I did.

1 like
thomaskim's avatar

bcrypt is a global helper function for Laravel. If you take a look at the source code, you will see this line of code:

return app('hash')->make($value, $options);

So, essentially, you can just do this to achieve the same thing in Lumen.

$hashedPassword = app('hash')->make($plainPassword);

This will ultimately use the BcryptHasher class so if you want, you can use that class directly.

use Illuminate\Hashing\BcryptHasher;

...
$hashedPassword = (new BcryptHasher)->make($plainPassword);

You can also use method injection.

5 likes
jekinney's avatar

That's right, crypt is php and in lumen cfg file in commenting or adding the facade() allows access to bcrypt. Soory bad info at the start.

mstnorris's avatar

@thomaskim the app('hash')->make('password') works, but why doesn't referencing bcrypt directly? Is it not available in Lumen?

@jekinney using the facades doesn't help :/

1 like
jekinney's avatar

Something not right, Maybe version thing, my Lumen 5.0 works fine with the bcrypt()... Weird, but I haven't touched Lumen 5.1 or 5.2 as I haven't needed it yet.

vipindasks's avatar

@mstnorris Can you please add below block to helpers.php in \vendor\laravel\lumen-framework\src\helpers.php

      if (! function_exists('bcrypt')) {
       /**
        * Hash the given value.
        *
        * @param  string  $value
        * @param  array   $options
        * @return string
        */
        function bcrypt($value, $options = [])
        {
           return app('hash')->make($value, $options);
        }
      }

Or, you can create a custom helper file and use the above code. You should be able to use bcrypt as usual by then. Make sure that

$app->withFacades();

is uncommented in bootstrap/app.php

Please or to participate in this conversation.