CakePHP 2 – Hashing passwords before saving.

A quick gotcha here that leverages CakePHP’s inbuilt utilities to hash data before you commit it to the database.

The beauty of this method is that you can still run all your validation checks and then hash the data between validation and saving. Why is that important? Consider you have a rule that says a password should be no more than 15 characters. When you hash it, it would break the rule and your record would never save.

All you have to do is hash your fields in the beforeSave function of your model like this example from a User Model:

public function beforeSave() {
if(!empty($this->data['User']['password'])) {
$this->data['User']['password'] = Security::hash($this->data['User']['password']);
return true;

One import aspect of this is to always return true. If you don’t your record will NEVER save.

One thought on “CakePHP 2 – Hashing passwords before saving.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>