Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel unique random string number

I would like to make an infinite string with a number. What is the best way to do this here e.g. mt_rand(1000000, 9000000) but if between 1000000 and 9000000 everything is occupied there are no more numbers. The more numbers are used the more often there are errors, and the if else has to rattle through the whole table again and again.

public function creating(Ticket $ticket)
{
    $randomNumber = mt_rand(1000000, 9000000);

    if(!Ticket::where('number', '=', $randomNumber)->exists()) {
        $ticket->fill(['number' => $randomNumber]);
    } else {
        $this->creating($ticket);
    }
}

What is the best way to do this? I want it to be a Unique Numberetic String. Which has no end.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To guarantee a unique number you should instead use created. Whenever a ticked is created, you can prepend some random numbers to the id to generate a unique number. Try this

public function created(Ticket $ticket) {
    $ticked->number = rand(1000, 9999).str_pad($ticked->id, 3, STR_PAD_LEFT);
    $ticked->save();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading