random() and uuid()

Generate random strings and UUIDs.

Syntax\Illuminate\Support\Str::random(16);

The Str::random() method returns a random alphanumeric string of the given length — useful for tokens. Str::uuid() generates a universally unique identifier (UUID v4).

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A password-reset controller generates a cryptographically random 64-character token with Str::random() and stores its hash in the database.
  • A file-upload service prefixes every uploaded file with Str::random(16) to prevent filename collisions in shared storage.
  • An API provisioning flow uses Str::uuid() as the primary key for new client records to ensure global uniqueness across distributed databases.

More examples

Generate a random token

Str::random() returns a cryptographically secure alphanumeric string of the given length, suitable for password-reset tokens.

Example · php
use Illuminate\Support\Str;

$token = Str::random(64);
// => e.g. 'aB3xQ9...' (64 alphanumeric characters)

// Store the hash, send the raw token
$hashed = hash('sha256', $token);

UUID as a primary key

Assigns a UUID generated by Str::uuid() as the model's primary key before it is inserted into the database.

Example · php
use Illuminate\Support\Str;

// In a model boot method
protected static function boot(): void
{
    parent::boot();

    static::creating(function ($model) {
        $model->id = (string) Str::uuid();
    });
}

Ordered UUID for sortable IDs

Str::orderedUuid() generates time-ordered UUIDs that sort correctly as strings, avoiding random-UUID index fragmentation in databases.

Example · php
use Illuminate\Support\Str;

$uuid1 = (string) Str::orderedUuid();
$uuid2 = (string) Str::orderedUuid();

// $uuid1 < $uuid2 when compared lexicographically
// Safe to use as a sortable indexed primary key in MySQL/PostgreSQL

Discussion

  • Be the first to comment on this lesson.