phplaraveluniqueidentifier

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.


Solution

  • You can use the PHP function like this:

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

    The output looks like this:

    s5s108dfc
    

    Here are the specifications:

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

    use Illuminate\Support\Str;
    $uniqid = Str::random(9);
    

    :::NOTE:::

    While this function may produce unique codes for a certain period, it is not guaranteed to always generate unique codes. You should need to cross-check every time with existing codes in your system.