如何改进这个随机促销代码生成器脚本? [重复]

This question already has an answer here:

I have this script that generates random promo codes.

    }
    $length = 10;
    $characters = '123456789ABCDEFGHJKMNPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $event = $request->event;
    $prefix = $request->prefix;
    $quantity = $request->quantity;
    $randomString = '';
    for ($x = 0; $x <= $quantity; $x++) {
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }

        $pin = "$prefix"."$randomString";
        $exists = Pin::where('pin', $pin)->first();
        if(!$exists){
            $new['pin'] = $pin;
            $new['event'] = $event;
            $new['user'] = '';
            Pin::create($new);
        }

        $randomString = '';
    }

It works but needs to be optimized as it can take forever to execute when the $quantity gets above a couple thousand.

I suspect the time hog is the bit that is looking if the pin exists. I am sure there must be a more efficient way to ensure the random strings are unique.

Thoughts? Thanks!

****** As pointed out random hash generation has been addressed here ******

Perhaps a part 2 to this question then...

Client has requested a set selection of chars for the random codes - '123456789ABCDEFGHJKMNPQRSTUVWXYZ'. Is there a way to limit the chars output by md5 hash?

</div>

A much simpler way:

$randomString = sha1(rand(0, 2000));