Table of contents

Generate Unique Random Numbers in Laravel

If you thinking about how to generate unique random numbers in Laravel from your database this. Then this post could help you to do that. For example, if you have an item that generates a random number but is unique. So to do that we need to generate the random numbers the check to our database if exists if not then use the generated number.

 

Here is the code that can generate random and unique numbers.

 

function ticket_number()
{
    do {
        $number = random_int(1000000, 9999999);
    } while (Ticket::where("number", "=", $number)->first());

    return $number;
}

 

As you can see it will not stop until the number generated is not unique using do while statement.

 

$data = [
      'number' => ticket_number(),
      'subject' => 'Sample subject',
      'description' => 'This is the description sample'
];
  
$ticket = Ticket::create($data);

 

Then in your controller for storing new tickets let's call the ticket_number function that generates the unique numbers.

 

That's it I hope it helps :)