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 ?
/**
* 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);
}
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