Home > Mobile >  How to hash password element of array in laravel?
How to hash password element of array in laravel?

Time:01-10

I have class UserService which has 2 functions. CreateUser() add user to database and hashPassword() hash password. But now I have a problem with hash password. Show me error password_hash(): Argument #1 ($password) must be of type string, array given. So what could I resolve this problem ?

class UserService
{
    public function createUser(RegistrationRequest $request): void
    {
        $this->hashPassword($request->correctValidate());
        User::create($request);
    }

    private function hashPassword($request)
    {
        $password = $request['password'] = Hash::make($request);
      return $password;

    }

}
public function correctValidate()
{
    return $this->validated();
}

CodePudding user response:

If you add something like this to the user model, it will do it automatically.

public function setPasswordAttribute($value) {
    $this->attributes['password'] = Hash::make($value);
}

CodePudding user response:

Will this work? ....

private function hashPassword($request)
{
    
  return Hash::make($request->input('password'));

}

....

CodePudding user response:

This error message is indicating that the function password_hash() was called with an argument that is an array, but the function expects the argument to be of type string.

It is likely that you have passed an array to the function instead of a string. You can try passing a string as the argument instead of an array.

CodePudding user response:

The Hash::make function is requiring you to pass string, hence $request in hashPassword should be string also.

There's many ways for you to solve this. As long as you pass string to the Hash::make function you should be golden.

You should learn how to be able to pass data properly. Its pretty much straightforward, if you pass string to a function that function will receive a string.

To answer your problem, this is one solution:

public function createUser(RegistrationRequest $request): void
{
    $validated = $request->correctValidate();
    $this->hashPassword($validated['password']);
    User::create($request);
}
  • Related