Generate Random Number in Laravel
Generate Random Number in Laravel

How to Generate Random Number in Laravel

How to Generate Random Number in Laravel


Hello learners, in this article, we will learn how to generate random number in Laravel. So let’s get started.

In Laravel, we can generate a random number using the random() helper function of Laravel. This helper function generates a cryptographically secure random number using PHP’s random_int() function internally. Implementation is so easy. Here’s how we can use it:

$randomNumber = random_int($min, $max);

Here in the implementation, $min and $max are the minimum and maximum values for the range of random numbers we want to generate.


For example, if we want to generate a random number between 1000 and 9999, our code will be like:

$randomNumber = random_int(1000, 9999);


We just have to make sure to import the necessary namespace if we are not already in a context/scope where random_int() is available:

use Illuminate\Support\Facades\{Random};

For instance, here in Laravel, the Illuminate\Support\Facades\Random class is a facade that provides access to the random_int() function, which generates cryptographically secure random integers. Also you probably know that, Facades in Laravel provide a “static” interface to classes available in the service container.

Using facades allows us to access Laravel’s services in a concise and expressive manner without needing to instantiate objects or manage dependencies manually.

So, when you use use Illuminate\Support\Facades\Random;, we are importing the Random Facade, which gives you access to methods like random_int() for generating random integers in a secure manner.

And then we can easily can call Random::randomInt():

$randomNumber = Random::randomInt($min, $max);

Remember to replace $min and $max with your desired range of random numbers as i showed previously.


Check Out More Resources if you like this one:

YouTube Channel:
WordPress Playlist:
Tools Playlist:

WordPress Tutorials:
Laravel Tutorials:
PHP Tutorials:
SQL Tutorials:
Various Tips:
Useful Tools:




#Laravel #Function #PHP


That’s All. Feel free to knock me. Thanks.

Editorial Staff

A Learner and trying to share what I learned!