Table of contents
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 :)
Read next