1

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.

3
  • Where is the creating method defined? Commented Feb 12, 2022 at 20:33
  • Its in a observer when creating Commented Feb 12, 2022 at 20:36
  • Do you need only numbers or are alphanumeric strings ok? Ex.: 29b3Fg9 Commented Feb 12, 2022 at 22:00

1 Answer 1

2

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();
}
Sign up to request clarification or add additional context in comments.

4 Comments

Now its better to use the timestamp see up comment from Muhammad Tashfeen or ur... what you are say
Timestamps are never unique. What if multiple records are to be created at the same time?
Yes, but what is when between 1000 and 9999 all numbers used with the 3 offsets.. yk
See rand(1000, 9999) is to prepend some random numbers to the id you can completely ignore it. The id is the real deal. Since it is coming from the database, it is guaranteed to always be unique.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.