We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Hash a password before create

Hi,

is there a way to pass data into the beforeCreate() method ?

I wanna do s.th. like this:

public function beforeCreate($password)
{
    $this->created_at = date('Y-m-d H:i:s');
    $this->updated_at = date('Y-m-d H:i:s');
    $this->password = $this->getDI()->getSecurity()->hash($password);
}

Ideas ? Thanks



98.9k
Accepted
answer

You can use a temporary property in your model to store the password and then it use right there in 'beforeCreate':

class Users extends Phalcon\Mvc\Model
{

    public $id;

    public $password;

    public $tempPassword;

    public $created_at;

    public $updated_at;

}

Assign the password onto that property:

$user = new Users;
$user->tempPassword = 'secret';

Take the password value from that column:

public function beforeCreate()
{
    $this->created_at = date('Y-m-d H:i:s');
    $this->updated_at = date('Y-m-d H:i:s');
    $this->password = $this->getDI()->getSecurity()->hash($this->tempPassword);
}

works !! Thanks :)



11.2k

If you want your users to be able to update their passwords, i would recommend you to do that function on the beforeSave event. But beware, you have to check if the password is uncrypted (or is changed) before you hash it, else you will rehash a hashed password (and it will break your user login). You would do it like this : (note isLegacyHash is a function from the Security service to chekc if a string is a bCrypt hash)

public function beforeSave()
{
    if(!$this->getDI()->get('security')->isLegacyHash($this->password)) {
        $this->password = $this->getDI()->get('security')->hash($this->password);
    }
    $this->updated_at = date('Y-m-d H:i:s');
}