简体   繁体   中英

Generate unique random ID for model

I'm fairly new with Laravel so please go easy on me :) I'm trying to work out the most efficient possible way of generating a unique random ID for a model. This ID should be 6 characters long so I'll be using mt_rand(100000,999999) to create it. What I want to do is on model creation, generate the ID, check it is truly unique and then save it against the model.

I've looked at observers to do this but it seems a little lengthy to tack onto the back of a creation event. Are there any alternatives or a way to call an observer without creating multiple files?

Chris.

If you want truly unique ID's I would look into UUID's to ensure that you never get any duplicates. I would suggest using this package: https://github.com/webpatser/laravel-uuid

You can easily generate a UUID using it by doing this: Uuid::generate(4); this will ensure that its truly random.

Ah right, managed to work this out :)

So rather than using events, I just extended the models boot method as this is another way of hooking into model events -

protected static function boot () {

    // run our parent boot
    parent::boot();

    // hook onto our creating method
    static::creating(function($model) {
        /** @var $model Candidate */
        $model->_generateAccessCode();
    });
}

This then tells the model that when a new one is being created (using the creating event), to generate a new access code.

I've then added the _generateAccessCode() method into the model -

/**
 * Called on Candidate model creation
 * @return void
 */
private function _generateAccessCode () {

    // make sure our value is unique by checking it doesn't exist already
    while(empty($this->access_code) || self::findByAccessCode($this->access_code, ['id'])) {
        $this->access_code = mt_rand(100000, 999999);
    }
}

Which references another method to verify an access code doesn't yet exist -

/**
 * Retrieve a candidate by access code
 * @param int $code 6 digit access code
 * @param array $columns Array of columns
 * @return mixed
 */
public static function findByAccessCode ($code, $columns = []) {

    if(count($columns) < 1) $columns = null;

    // get our candidate by access code
    $candidate = Candidate::where('access_code', '=', $code)->first($columns);

    // return our candidate
    return $candidate;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM