Site Admin
Site Admin Founder of MeaningArticles
1673 Views

Laravel Generate Random Unique Number

Hello Dev.

Now let's see example of how to generate random unique number in laravel?. we will learn you generate random unique number example in laravel. i am going to show you laravel generate random unique number example.

If you want to generate random 6 digit number then i will give you simple and easy example with solution and output. we will learn how to generate random unique number in laravel.

Here, i will give you two example where you can generate 4, 6, 8, 10 digit random number with laravel. you can also use this example with laravel 6, laravel 7 and laravel 8 version.

So let's see the below example step by step...


Example 1: 4 Digit Random Code

<?php
  
namespace App\Http\Controllers;
  
class TestController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $randomNumber = random_int(1000, 9999);
  
        dd($randomNumber);
    }
}

Output

4953


Example 2: Random Unique Number

<?php
  
namespace App\Http\Controllers;
  
use App\Models\Game;
  
class GameController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $input = [
            'name' => 'WCC2',
            'referal_code' => $this->generateUniqueCode()
        ];
  
        $game = Game::create($input);
  
        dd($game);
    }
    /**
     * Write referal_code on Method
     *
     * @return response()
     */
    public function generateUniqueCode()
    {
        do {
            $referal_code = random_int(100000, 999999);
        } while (Game::where("referal_code", "=", $referal_code)->first());
  
        return $referal_code;
    }
}

Output

Array
(
    [name] => WWC2
    [referal_code] => 753698
    [updated_at] => 2021-05-20T13:57:29.000000Z
    [created_at] => 2021-05-20T13:57:29.000000Z
    [id] => 1
)

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.