Can you use a package? You can use uuid, which are unique: https://packagist.org/packages/ramsey/uuid
Is the length important?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I've been using the using the following code snippet for sometime to generate unique numbers e.g customer no.s etc.
/*
* Generate unique random string
*
* @return string
*/
public function generaterandomString($length) {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$randStr = '' ;
while ($i <= $length) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$randStr = $randStr . $tmp;
$i++;
}
return $randStr;
}
I later realized that duplication occurs when dealing with a lot of records.
How can generate unique codes? Modification of the above snippet or suggestion of a new approach will be highly appreciated.
@kenprogrammer So this is laravel? Can you point to where it says that? :)
And why is the length important here ? If it is used to hide an id or similar you can use hashids: https://packagist.org/packages/hashids/hashids
Please or to participate in this conversation.