skip to Main Content

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();
}

3

Answers


  1. Will this work?
    ….

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

    ….

    Login or Signup to reply.
  2. 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);
    }
    
    Login or Signup to reply.
  3. 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);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search