Laravel Generate Random Unique Number

Laravel Generate Random Unique Number

To generate random unique number for a web application, there may be many different way but here in this i will give some easiest example to generate random unique numbers for laravel application. 

A question that can be arise in your mind, why we need to generate random unique number and where we need to use of these numbers. So the answer is very simple.

We all know about two factor authentication or one time password where we can easily verify our moder number or email id. So for this purposes we can use these numbers and there can be more other situation in the real world appication where we need to generage unique numbers. 

So let’s take examples or methods to generate 6 digit unique numbers in laravel application.

Example 1 

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

Example 2: 

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

In the first example method will return 6 digit random unique number and second example shows the use of randomly generated unique number for product code.