Home > Net >  Insert a random int that does not exist in Dtabase not working?
Insert a random int that does not exist in Dtabase not working?

Time:11-03

mt_rand() and random_int() both are generate only one numbe and insert it in database where the number is already exist. I want to clear that , I want to insert a random number that is not exist in database.

I took this code from here

In my case in laravel 8, the code looks like below

public function generateProductCode() {
    $number = mt_rand(1000000000, 9999999999); 

    // call the same function if the barcode exists in Dtabase already
    if ($this->productCodeExists($number)) {
        return $this->generateProductCode();
    }

    // otherwise, it's valid and can be used
    return $number;
}

public function productCodeExists($number) {
    // query the database and return a boolean
    // for instance, it might look like this in Laravel
    return Product::where('product_code', $number)->exists();
}

The model name is Product and DB table name is products. 'product_code' is the column where I want to do this query. In store function where I Call generateProductCode() function, it looks like below

public function store(Request $request)
{
    $product = new Product;
    //Generate a Product key
    $product->product_code = $this->generateProductCode();
    $product->save();
 }

It returns all time only one numbers that is 2147483647 . Photo is here What is the wrong? What is the perfect query to check exist so that it returns another that is not exist in the database.

CodePudding user response:

according to php doc:

mt_rand: This function does not generate cryptographically secure values, and should not be used for cryptographic purposes

you can use random_int

it Generates cryptographic random integers that are suitable for use where unbiased results are critical

 $number = random_int(1000000000, 9999999999); 

CodePudding user response:

You should create a recursion function check if the number is already used or not.

public function store(Request $request)
{
    $product = new Product;
    //Generate a Product key
    $product->product_code = $this->newRandomInt();
    $product->save();
 }

 private function newRandomInt()
    {
        $number = random_int(1000000000, 9999999999); 
        $isUsed =  Product::where('number', $number)->first();
        if ($isUsed) {
            return $this->newRandomInt();
        }
        return $number;
    }
  • Related