Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fdusautoir's avatar

Generate unique random string

Hi Everybody.

For my app, I need a string reference field for orders and it needs to be unique for sure I use Str_random(10) and check if it exists already before inserting, and loop around again if it does. That works well but I wonder if it exists a better approach to do that with L5 ?

0 likes
8 replies
wells's avatar

Timestamp with the row primary key is another way to skin the cat.

2 likes
bestmomo's avatar

With L5 there is quickRandom($length) (to not use for cryptography) and random($length) helpers.

1 like
pmall's avatar

@bestmomo didn't know this. That is great :) Do you know how the random strings are generated with these helpers ?

1 like
bestmomo's avatar

@pmall in Illuminate\Support\Str :

/**
 * Generate a more truly "random" alpha-numeric string.
 *
 * @param  int  $length
 * @return string
 *
 * @throws \RuntimeException
 */
public static function random($length = 16)
{
    if ( ! function_exists('openssl_random_pseudo_bytes'))
    {
        throw new RuntimeException('OpenSSL extension is required.');
    }

    $bytes = openssl_random_pseudo_bytes($length * 2);

    if ($bytes === false)
    {
        throw new RuntimeException('Unable to generate random string.');
    }

    return substr(str_replace(array('/', '+', '='), '', base64_encode($bytes)), 0, $length);
}

/**
 * Generate a "random" alpha-numeric string.
 *
 * Should not be considered sufficient for cryptography, etc.
 *
 * @param  int  $length
 * @return string
 */
public static function quickRandom($length = 16)
{
    $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

    return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
}
2 likes
wells's avatar

Gotta love Laravel helper functions

willvincent's avatar

Any reason you couldn't just generate an md5 checksum from microtime()?

$random_string = md5(microtime());

dd($random_string);

Technically speaking, that's not 'random' but it should be unique. Would be even better to concatenate order details with microtime, but in a pinch, that should be enough.

It sounds like really what you're after is generation of a uuid for an order though, in which case something like this may be a good option: https://github.com/webpatser/laravel-uuid

2 likes

Please or to participate in this conversation.