Nils Vennemann
Nils Vennemann

Reputation: 23

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.

Upvotes: 1

Views: 4907

Answers (1)

ruleboy21
ruleboy21

Reputation: 6363

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

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

Upvotes: 2

Related Questions