How to generate unique random value for each user in laravel and add it to database
Your logic isn't technically faulty. However, if your application attracts lots of users, fetching all of the random numbers may well become unnecessarily expensive, in terms of resources and computation time.
I would suggest another approach, where you generate a random number and then check it against the database.
function generateBarcodeNumber() {
$number = mt_rand(1000000000, 9999999999); // better than rand()
// call the same function if the barcode exists already
if (barcodeNumberExists($number)) {
return generateBarcodeNumber();
}
// otherwise, it's valid and can be used
return $number;
}
function barcodeNumberExists($number) {
// query the database and return a boolean
// for instance, it might look like this in Laravel
return User::whereBarcodeNumber($number)->exists();
}
In laravel how to create unique and random number
Per your request, here's how to implement the suggested answer with your code
public function store(Request $request)
{
$this->validate($request, [
'student_name' => 'required|string|max:255',
'student_father_name' => 'required|string|max:255',
'student_mother_name' => 'required|string|max:255',
'student_photo' => 'required|image|mimes:jpeg,png,jpg|max:2048',
]);
$input['student_photo'] = time().'.'.$request->student_photo->getClientOriginalExtension();
$folder1 = public_path('STUDENT_DATA/STUDENT_PHOTO/');
$path1 = $folder1 . $input['student_photo']; // path 1
$request->student_photo->move($folder1, $input['student_photo']); // image saved in first folder
$path2 = public_path('../../../abc.com/public/STUDENT_DATA/STUDENT_PHOTO/') . $input['student_photo']; // path 2
\File::copy($path1, $path2);
$input['student_name'] = strtoupper ($request['student_name']);
$input['student_father_name'] = strtoupper ($request['student_father_name']);
$input['student_mother_name'] = strtoupper ($request['student_mother_name']);
$id = $this->generateRegistrationId();
$input['student_registration_id'] = $id;
DB::table('locations')->insert([['center_code' => $id]])
Student::create($input);
return back()->with('success',' STUDENT REGISTERD SUCCESSFULLY .');
}
function generateRegistrationId() {
$id = 'SIIT_' . mt_rand(1000000000, 9999999999); // better than rand()
// call the same function if the id exists already
if ($this->registrationIdExists($id)) {
return $this->generateRegistrationId();
}
// otherwise, it's valid and can be used
return $id;
}
function registrationIdExists($id) {
// query the database and return a boolean
// for instance, it might look like this in Laravel
return Student::where('student_registration_id', $id)->exists();
}
Laravel unique random string number
To guarantee a unique number you should instead use created
. Whenever a ticket is created, you can prepend some random numbers to the id to generate a unique number. Try this
public function created(Ticket $ticket) {
$ticket->number = rand(1000, 9999).str_pad($ticket->id, 3, STR_PAD_LEFT);
$ticket->save();
}
Insert a random int that does not exist in Dtabase not working?
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;
}
How to generate and insert millions of random numbers in a database and then save it in Laravel?
if(!in_array($numbers, $number)
for testing the uniqueness will get slower and slower as your $numbers
list grows..... rather than setting the $number
as a value in the array, set it as the key, and then you can do a direct key check for duplication which is much faster than using in_array()
You're also adding $number
to $numbers
before doing the duplicates check, so you've already added the duplicate to your array (which is why it always fails)
The database check for every value is also a big overhead, best eliminated if you can do so
if(!isset($numbers[$number])) {
$this->pin->create(['number'=>$number,'user_id'=>$user->id]);
$numbers[$number] = true;
}else{
$i--;
}
How to concatenate primary key with random number in laravel?
Ok as you requested this is what I do usually
Please note I assume your table structure looks like below
id | userid | firstname | lastname | email | password
And userid
should be null in default
- After saved I retrieve the last inserted ID from db
- Then I customize the new ID as I wanted
- Then I saved it in new field (Updating table)
Here is the code
$userid = User::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'userid'=> $ra, // here i want to concatenate random number with primary key which is going
to be added
'password' => Hash::make($data['password']),
]);
Now lets fetch the last inserted id
$id = DB::getPdo()->lastInsertId();
Then lets make it as you wants
$random_id= rand(1000,10000)
$new_id = $id.'_'.$random_id;
Now update the database
//Updating row with registration number
User::where('id', $id)->update(['userid' => $new_id ]);
Thats all
Thanks
Related Topics
Php 7 With Phpmyadmin Gives Lots of Deprecation Notices
How to Stop PHP Code Execution
How to Update Field to Add Value to Existing Value
Failed to Open the System Default Web Browser. Is One Installed - Pgadmin4
Laravel 6: Call to Undefined Method App\\User::Createtoken()
Session Id Is Changing After Every Request
Windows 10 Docker:/Usr/Bin/Env: 'Php\R': No Such File or Directory
How to Extract and Access Data from Json With PHP
PHP Multidimensional Array Search by Value
Show a Number to Two Decimal Places
Check If Username and Email Already Exists in Database
How to Convert Text to Svg Paths
How to Remove a Key from an Object Not Array in Laravel
Laravel - Page Not Found Even That the Route Exists
Easiest Way to Replace All Characters in Even Positions in a String.
Internal Server Error While Run Laravel on Localhost
404 Not Found; Apache Server Can't Load Simple PHP File
PHP Code Is Not Being Executed, But the Code Shows in the Browser Source Code