How to store Hashed Password to the Database using Laravel 5.8

1.2k Views Asked by At

I need to store Password as hashed to the database, I was able to has the password but when I submit my form the password stores as un-hashed,

Here's my controller Store Function

 public function store(Request $request)
{

    $hash = ['password' => Hash::make($request)];

    //dd($hash);
    // HASHED PASSWORD WAS DISPLAYED HERE 


    $user = User::create($this->validateRequest());

    dd('User Created');
}

Here's my Validate Function

private function validateRequest()
{

    return request()->validate([
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
        'phone' => 'required',
    ]);
}

I tried to do this in my Store Function (But it didn't work !!)

public function store(Request $request)
    {

        $hash = ['password' => Hash::make($request)];

        $user = User::create($this->validateRequest($hash));
        dd('User Created');
   }

Is there a way where I can store the hashed password to the DB by this way ?

Or else do I need to stick to this way ;( ?

$user = User::create([
            'name' => $request['name'],
            'phone' => $request['phone'],
            'email' => $request['email'],
            'password' => Hash::make($request['password']),
        ]);

I just wanted my controllers to be clean with few lines of code.

Can someone please help me out.

Thanks

2

There are 2 best solutions below

0
On BEST ANSWER

Use a mutator in your User model so every time you set the password, it'll be hashed.

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

This way, you store method would look like this:

public function store(Request $request)
{
    $user = User::create($this->validateRequest());
    dd('User Created');
}

This is outside the scope of this question but just one more advice: you should use a form request class (https://laravel.com/docs/8.x/validation#creating-form-requests) in order to reduce the amount of code in your controllers (among other advantages).

1
On

You're validating the request after changing the value of password, for this reason password confirmation can't be validated and returning with validation error.

Validate the request first, then replace the password value with hashed one.

public function store(Request $request)
{
    $request->validate([
      'name' => ['required', 'string', 'max:255'],
      'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
      'password' => ['required', 'string', 'min:8', 'confirmed'],
      'phone' => 'required',
    ]);
    
    $request->merge(['password' => Hash::make($request->input('password'))]);

    $user = User::create($request->all());
    dd($user);
}