I want to create an id, that contains int value and string value, with 4 characters and it must be unique because it's a primarykey.
for example: 1g81 or h39d.
I am using laravel 8.8.
CodePudding user response:
In PHP
use this:
function unique_code($limit)
{
return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $limit);
}
echo unique_code(4);
$limit
= number of characters
or in laravel
you can use only this:
define this on the top
use Illuminate\Support\Str;
and use this
$uniqid = Str::random(4);
CodePudding user response:
In MySQL,the uuid()
function generates a pseudo random string which looks like da5c3e92-c06e-11ec-a98b-000c29087583
. With the left() function, we can fetch the first 4 characters. To demonstrate, create a table named idtest
. Then insert into the table with characters generated with the said functions. If case the generated string is already used, we can use a loop to generate another one to gurantee its uniqueness.
create table idtest(id char(4) primary key);
delimiter //
drop procedure if exists generate_id //
create procedure generate_id(num int unsigned)
begin
declare count int default 0;
while count<num do
lp:loop
select left(uuid(),4) into @id;
if (select count(*) from idtest where id=@id ) =0 then
insert idtest (id) values (@id);
leave lp;
end if;
end loop lp;
set count=count 1;
end while;
end//
call generate_id(100)// -- call the procedure to insert 100 strings into the table
CodePudding user response:
You Can use the below custom function to generate random strings with numbers too.
$n=4;
function getName($n) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $n; $i ) {
$index = rand(0, strlen($characters) - 1);
$randomString .= $characters[$index];
}
return $randomString;
}
echo getName($n)
;
CodePudding user response:
Here's a simple method that will guarantee that your ID is always unique:
public function generateId(){
$uuid = Uuid::generate(4)->string; //Webpaster UUID generator
$id = explode('-', $uuid)[0]; //Taking first block of random strings/numbers that is separated with "-"
//Check if ID unique, if not, generate another one with same logic
while(YourModel::where('id', $id)->first()){
$uuid = Uuid::generate(4)->string;
$id = explode('-', $uuid)[0];
}
return $id;
}
This will basically re-generate the code each time one is already found in your database. The package used here is this one: https://github.com/webpatser/laravel-uuid
You can basically remove the package and use Laravel's random() method, and just keep the same logic for regenerating the string if it is already found in the database.