简体   繁体   中英

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.

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);

You can generate a random string with this library:

use Illuminate\Support\Str;

$id = Str::random(9);

You can use this,

$unique_id= echo floor(time()-999999999);

this is generating a 9 digit unique value based on time.

Generate custom Unique ID or Code (With Prefix or Suffix Or Both Or Only Unique Id) Or reset your ID after the change of Prefix or Suffix Or Both in laravel framework

Visit https://github.com/SirajCse/laravel-unique-id-generator

Example: Inv-000001/12/21

UniqueIdGenerator::generate(['table' => 'invoices','field'=>'invoice_id','length' => 16,'prefix' => 'Inv-', 'suffix' => date('/m/y')]);

'table' => 'invoices' [sting table name]
'field'=>'invoice_id' [Default 'id'] [Optional][any string field name]
'length' => 12 [Integer value Id length]
'prefix'=>'Inv-' [Default ''] [Optional] [any string]
'suffix'=>date('/m/y') [Default ''] [Optional][any string]
'reset_on_change'=>false[ Default false] [Optional] [Options are 1.prefix , 2.suffix 3.both 4.false]
uniqueId=000001

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM