How to Generate Random Unique Number in Laravel?

By Hardik Savani April 16, 2024 Category : 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...

Tags :
Shares