Home > Mobile >  Laravel unique random string number
Laravel unique random string number

Time:02-13

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.

CodePudding user response:

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

CodePudding user response:

You can use the current timestamp which will produce a unique number most of the time.

$randomNumber = Illuminate\Support\Carbon::now()->timestamp;
  • Related