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.