During my current project i have a need for generating alot of unique keys like API keys or all kinds of tokens.
I was surprised that Laravel did not implement something this trivial already, so i decided to create a helper for myself.
You may use this helper for you own projects if you like.
How -to use:
If you dont have a helper file already, you can you create a file like app/Helpers/string.php.
There paste this code:
<?php
if( ! function_exists('unique_random') ){
/**
*
* Generate a unique random string of characters
* uses str_random() helper for generating the random string
*
* @param $table - name of the table
* @param $col - name of the column that needs to be tested
* @param int $chars - length of the random string
*
* @return string
*/
function unique_random($table, $col, $chars = 16){
$unique = false;
// Store tested results in array to not test them again
$tested = [];
do{
// Generate random string of characters
$random = str_random($chars);
// Check if it's already testing
// If so, don't query the database again
if( in_array($random, $tested) ){
continue;
}
// Check if it is unique in the database
$count = DB::table($table)->where($col, '=', $random)->count();
// Store the random character in the tested array
// To keep track which ones are already tested
$tested[] = $random;
// String appears to be unique
if( $count == 0){
// Set unique to true to break the loop
$unique = true;
}
// If unique is still false at this point
// it will just repeat all the steps until
// it has generated a random string of characters
}
while(!$unique);
return $random;
}
}
After that, go to composer.json and add this code to the "autoload" block:
"autoload": {
"classmap": [
"database"
],
"files": [
"app/Helpers/string.php" // <-- Add this
],
"psr-4": {
"App\\": "app/"
}
},
Run the following command:
composer dump-autoload
Now you should be able to use it as:
$uniqueString = unique_random('users', 'auth_token', 40);