ItSolutionStuff.com

How to Generate Random Unique Number in Laravel?

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

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel 8 Barcode Generator Example

Read Now →

Laravel 8 QR Code Generate Example

Read Now →

How to Generate PDF and Send Email in Laravel?

Read Now →

How to Create Custom Helper Function in Laravel 7?

Read Now →

How to Check if String Contains Specific Word in Laravel?

Read Now →

How to Generate UUID in Laravel?

Read Now →

How to get Keys from Array in PHP Laravel?

Read Now →

Laravel Redirect to URL using redirect() Helper

Read Now →

How to Generate Random Unique String in Laravel?

Read Now →

Laravel - Generate Captcha code and Validation example using BotDetect package

Read Now →

How to Generate Random Alphanumeric String in PHP?

Read Now →