[CakePHP]How to make random id in Model


Sometimes, we want to save random unique id to database. Then, please add this method.

 * generate random unique id
 * @return int random unique id
 * @access public
    function randomUniqueId() {
        $rand = mt_rand(1, 99999999);

        // if rand value already exist, try again
        if ($this->find('count', array('conditions' => array('Model.field_name' => $rand))) > 0) {
            return $this->randomUniqueId();
        return $rand;

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.