valorin/random
Laravel helper for generating random strings, numbers, and values with a clean API. Create secure tokens, readable IDs, and randomized data for testing or seeding, with configurable length, character sets, and formats.
Installation:
composer require valorin/random
No service provider or facade registration is required—use it as a standalone helper.
First Use Case: Generate a secure random string (e.g., for API tokens, passwords, or test data):
use Valorin\Random\Facades\Random;
$randomString = Random::string(32); // 32-character alphanumeric string
Key Classes:
Random::string($length) – Alphanumeric strings.Random::uuid() – RFC 4122 UUIDs.Random::int($min, $max) – Cryptographically secure integers.Random::hex($length) – Hexadecimal strings.Random::bool() – Random boolean.Where to Look First:
vendor/valorin/random/src/Random.php for core logic.tests/) for edge cases (e.g., Random::int(1, 1)).// API token (64 chars, alphanumeric + symbols)
$token = Random::string(64, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*');
// Store in DB with hashed variant (if needed)
$user->api_token = hash('sha256', $token);
// Faker alternative for deterministic testing
$fakeEmail = Random::string(10) . '@example.com';
$fakeId = Random::uuid();
// Seed a Laravel model factory with random data
$user = User::factory()->create([
'email' => Random::string(8) . '@test.com',
'password' => Random::string(12),
]);
$token = Random::string(60);
Password::createToken($user)->token = $token;
$key = Random::hex(16); // Unique key for throttling
$customChars = 'ABC123!';
$random = Random::string(5, $customChars); // e.g., "A1B!C"
$ids = collect(range(1, 100))->map(fn() => Random::uuid());
str_random() (Laravel’s legacy helper). Cache results if regenerating frequently.
$cachedTokens = cache()->remember('api_tokens', now()->addHours(1), function() {
return collect(range(1, 100))->map(fn() => Random::string(32));
});
Non-Uniform Distributions:
Random::int($min, $max) uses random_int(), which is uniform, but custom character sets may skew probability. Verify with:
$freq = collect(range(1, 1000))->map(fn() => Random::string(1, '01'))->valueCounts();
// Should be ~50/50 for '0' and '1'.
UUID Collisions:
Character Set Validation:
$chars = 'abc';
if (preg_match('/[^a-z]/', $chars)) {
throw new \InvalidArgumentException('Only lowercase letters allowed.');
}
Laravel Caching Interactions:
Random::string() in cached views, ensure the randomness isn’t memoized unintentionally:
// Bad: Cache includes randomness
Cache::remember('page', now()->addMinutes(5), function() {
return view('page', ['token' => Random::string(10)]);
});
// Good: Generate on demand
return view('page', ['token' => Random::string(10)]);
Deterministic Testing:
Random::shouldReceive('string')->andReturn('fixed123');
Random::setSeed($seed) (if available) for reproducible results.Character Set Issues:
$chars = '!@#$%^&*()';
$sample = Random::string(10, $chars);
var_dump(str_split($sample)); // Verify no unexpected chars.
Performance Bottlenecks:
php -dpcntl.profiler=1 -n artisan tinker
Look for random_int() calls in Xdebug traces.Custom Random Sources:
random_int() by binding a custom RandomGenerator:
$app->bind(\Valorin\Random\RandomGenerator::class, function() {
return new \Custom\SecureGenerator();
});
Additional Methods:
namespace App\Extensions;
use Valorin\Random\Facades\Random as BaseRandom;
class Random extends BaseRandom {
public static function slug($length = 10) {
return static::string($length, 'abcdefghijklmnopqrstuvwxyz-');
}
}
Configuration:
config(['random.default_length' => 32]);
// In a macro or helper:
Random::string(config('random.default_length'));
Artisan Commands:
$this->info('Reset token: ' . Random::string(60));
Queue Jobs:
$job = new ProcessPodcast(Random::uuid());
ProcessPodcastJob::dispatch($job);
Migration Rollbacks:
$fakeData = collect(range(1, 10))->map(fn() => [
'id' => Random::uuid(),
'name' => Random::string(10),
]);
How can I help you explore Laravel packages today?