Can't get Laravel login form to store passwords using hash

Laravel keeps the username and email in order, but doesn't store anything for the password field when I add the hash function. My controller code:

public function store()
{
    $data = Input::only(['username','email','password' => Hash::make('password')]);

    $newUser = User::create($data);

    if($newUser)
    {
        Auth::login($newUser);
        return Redirect::route('profile');
    }
    return Redirect::route('user.create')->withInput();
}

      

With this code, the database field for the password is simply left blank after a new user is registered. Plain text password inserts ok when I remove the hash function. Passwords need to be stored in hashed form after users submit their information. When I seed the database using the wizard, the hash function works fine, but not when I use it in my controller logic. Can anyone please help?

EDIT: In User.php

protected $fillable = ['username','email','password'];

      

+3


source to share


1 answer


Ok, so besides the fact that the code you have above won't work, you are going about it wrong.

First, the method you are trying to do would be:

$input = Input::only(['username', 'email', 'password']);
$input['password'] = Hash::make($input['password']);

      

The approach you use to set the value only won't work, and besides, you have Hash::make('password')

one that will use the hash of the "password" every time, not a variable, but a word. Input::only()

takes an array of returned field names, so it uses the array values, not the key. The array ['password' => Hash::make('password')]

has the hash value of the word password, not the password.

The best approach would be like this:



$input = Input::only(['username', 'email', 'password']);
$user = User::create($input);

      

Then in your model User

, you have:

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

      

This means you don't have to worry about hashing and can trust the model to do it for you.

Also, if the memory is serving Auth::login()

takes an integer and not a model, so it would be Auth::login($newUser->id)

logging in to the user who just logged in, although I would highly recommend some kind of email validation / activation.

+8


source







All Articles