Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AndrewBen's avatar

Hello, How can i Auto generate specific numbers in Laravel (not ID)

This is what i want to do. I want all item on a database table to have a specific number 5 to eight digits long. this number is not the id number of the item,

I have this javascript code that does it for me

<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a random number between 1 and 100.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
    var x = document.getElementById("demo")
    x.innerHTML = Math.floor((Math.random() * 1000000000000) * 4000);
}
</script>
</body>
</html>

now i don't trust javascript because i don't want the numbers to repeat in the future. i want to do this with php or laravel. how can i make this happen

0 likes
5 replies
SaeedPrez's avatar

@AndrewBen what do you mean same number? You give it a minimum and a maximum, it will generate a random number between the min and max.

SaeedPrez's avatar
Level 50

If you want a unique number that does not already exist in your database, you can do this..

// Get all existing numbers in database
$ids = App\Model::pluck('unique_column');

// Generate a new unique number
do {
    $id = rand(1000, 9999);
} while (in_array($id, $ids));

echo $id . ' is unique';
4 likes
HarisMansoor's avatar

Or if you want to generate a number of predefined lenght like Invoice Ids (same as id but with leading 0s)



     $statement = \DB::select("show table status like 'invoices'");

     $invoice_number=  str_pad($statement[0]->Auto_increment, 5, '0', STR_PAD_LEFT); 
 

Please or to participate in this conversation.