How to Generate Random Unique Number in Laravel?
Hi Dev,
Now, let's see tutorial of generate 6 digit random number in laravel. i would like to show you how to generate 6 digit random number in laravel. if you have question about laravel generate random 6 digit number then i will give simple example with solution. you will learn how to generate random unique number in laravel.
In this post, i will give you two example where you can generate 4, 6, 8, 10 digit random number with laravel and you can learn how to generate random unique number in laravel. you can also use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version.
let's see both example:
Example 1: 6 Digit Random Code
<?php
namespace App\Http\Controllers;
class ITSController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$randomNumber = random_int(100000, 999999);
dd($randomNumber);
}
}
Output:
192004
Example 2: Random Unique Number
<?php
namespace App\Http\Controllers;
use App\Models\Product;
class ITSController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$input = [
'name' => 'Silver',
'price' => 100,
'code' => $this->generateUniqueCode()
];
$product = Product::create($input);
dd($product);
}
/**
* Write code on Method
*
* @return response()
*/
public function generateUniqueCode()
{
do {
$code = random_int(100000, 999999);
} while (Product::where("code", "=", $code)->first());
return $code;
}
}
Output:
Array
(
[name] => Silver
[price] => 100
[code] => 586955
[updated_at] => 2021-05-20T13:57:29.000000Z
[created_at] => 2021-05-20T13:57:29.000000Z
[id] => 101
)
now you can check from your end.
i hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel 8 Barcode Generator Example
- Laravel 8 QR Code Generate Example
- How to Generate PDF and Send Email in Laravel?
- How to Create Custom Helper Function in Laravel 7?
- How to Check if String Contains Specific Word in Laravel?
- How to Generate UUID in Laravel?
- How to get Keys from Array in PHP Laravel?
- Laravel Redirect to URL using redirect() Helper
- How to Generate Random Unique String in Laravel?
- Laravel - Generate Captcha code and Validation example using BotDetect package
- How to Generate Random Alphanumeric String in PHP?