Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Random Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require valorin/random
    

    No service provider or facade registration is required—use it as a standalone helper.

  2. 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
    
  3. 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.
  4. Where to Look First:

    • Facade API docs (if available).
    • vendor/valorin/random/src/Random.php for core logic.
    • Test cases (tests/) for edge cases (e.g., Random::int(1, 1)).

Implementation Patterns

Common Workflows

1. Generating Secure Tokens

// 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);

2. Test Data Factories

// Faker alternative for deterministic testing
$fakeEmail = Random::string(10) . '@example.com';
$fakeId = Random::uuid();

3. Randomized Seeding

// Seed a Laravel model factory with random data
$user = User::factory()->create([
    'email' => Random::string(8) . '@test.com',
    'password' => Random::string(12),
]);

4. Integration with Laravel Features

  • Password Reset Tokens:
    $token = Random::string(60);
    Password::createToken($user)->token = $token;
    
  • Rate Limiting:
    $key = Random::hex(16); // Unique key for throttling
    

5. Custom Character Sets

$customChars = 'ABC123!';
$random = Random::string(5, $customChars); // e.g., "A1B!C"

6. Batch Generation

$ids = collect(range(1, 100))->map(fn() => Random::uuid());

Performance Considerations

  • Avoid in Loops: Cryptographic randomness is slower than 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));
    });
    

Gotchas and Tips

Pitfalls

  1. 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'.
      
  2. UUID Collisions:

    • While astronomically unlikely, UUIDv4 collisions can occur. For critical systems, append a timestamp or use UUIDv7 (if supported).
  3. Character Set Validation:

    • Empty or invalid character sets throw exceptions. Validate inputs:
      $chars = 'abc';
      if (preg_match('/[^a-z]/', $chars)) {
          throw new \InvalidArgumentException('Only lowercase letters allowed.');
      }
      
  4. Laravel Caching Interactions:

    • If using 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)]);
      

Debugging

  1. Deterministic Testing:

    • Mock the facade for tests:
      Random::shouldReceive('string')->andReturn('fixed123');
      
    • Use Random::setSeed($seed) (if available) for reproducible results.
  2. Character Set Issues:

    • Debug with:
      $chars = '!@#$%^&*()';
      $sample = Random::string(10, $chars);
      var_dump(str_split($sample)); // Verify no unexpected chars.
      
  3. Performance Bottlenecks:

    • Profile with:
      php -dpcntl.profiler=1 -n artisan tinker
      
      Look for random_int() calls in Xdebug traces.

Extension Points

  1. Custom Random Sources:

    • Override the underlying random_int() by binding a custom RandomGenerator:
      $app->bind(\Valorin\Random\RandomGenerator::class, function() {
          return new \Custom\SecureGenerator();
      });
      
  2. Additional Methods:

    • Extend the facade:
      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-');
          }
      }
      
  3. Configuration:

    • No built-in config, but you can wrap the facade for defaults:
      config(['random.default_length' => 32]);
      
      // In a macro or helper:
      Random::string(config('random.default_length'));
      

Laravel-Specific Tips

  1. Artisan Commands:

    • Generate random data in commands:
      $this->info('Reset token: ' . Random::string(60));
      
  2. Queue Jobs:

    • Use for disposable job IDs:
      $job = new ProcessPodcast(Random::uuid());
      ProcessPodcastJob::dispatch($job);
      
  3. Migration Rollbacks:

    • Generate fake data for rollback testing:
      $fakeData = collect(range(1, 10))->map(fn() => [
          'id' => Random::uuid(),
          'name' => Random::string(10),
      ]);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle