Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can generate the unique ID in laravel?

I’m working with my graduation project in Laravel, and want to generate small unique ID "9 char max" ... I don't need UUID because this will generate 36 char which is too long.

like image 236
shrooq Avatar asked Dec 01 '22 09:12

shrooq


2 Answers

You can use PHP function like this:

function unique_code($limit)
{
  return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $limit);
}
echo unique_code(9);

Output looks like:

s5s108dfc

Here the specifications:

  • base_convert – Convert a number between arbitrary bases.
  • sha1 – Calculate the sha1 hash of a string.
  • uniqid – Generate a unique ID.
  • mt_rand – Generate a random value via the Mersenne Twister Random Number Generator.

Or in Laravel you can use laravel Str library: just use this:

use Illuminate\Support\Str;
$uniqid = Str::random(9);
like image 136
nayeemdev Avatar answered Dec 03 '22 22:12

nayeemdev


You can generate a random string with this library:

use Illuminate\Support\Str;

$id = Str::random(9);

like image 26
Marcos Messias Avatar answered Dec 03 '22 22:12

Marcos Messias