Str::createUuidsUsing()
Override UUID generation in tests with predictable values — make your tests deterministic without mocking.
Overview
Str::createUuidsUsing() lets you replace Laravel's UUID generator with a custom callback. In tests, this means you can produce predictable, known UUIDs instead of random ones, making assertions straightforward.
Usage
use Illuminate\Support\Str;
test('order gets a predictable UUID', function () {
Str::createUuidsUsing(fn () => 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee');
$order = Order::create(['total' => 5000]);
expect($order->uuid)->toBe('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee');
// Don't forget to reset!
Str::createUuidsNormally();
});
Generate sequential UUIDs for multiple records:
$counter = 0;
Str::createUuidsUsing(function () use (&$counter) {
$counter++;
return "00000000-0000-0000-0000-" . str_pad($counter, 12, '0', STR_PAD_LEFT);
});
$first = Str::uuid(); // 00000000-0000-0000-0000-000000000001
$second = Str::uuid(); // 00000000-0000-0000-0000-000000000002
Freeze UUIDs
If you want every Str::uuid() call to return the same value:
$uuid = Str::freezeUuids();
Str::uuid(); // Same as $uuid
Str::uuid(); // Same as $uuid
Str::createUuidsNormally(); // Resume random UUIDs
Similar Methods
The same pattern works for ULIDs and ordered UUIDs:
Str::createUlidsUsing(fn () => '01H2XYZ...');
Str::freezeUlids();
Str::createUlidsNormally();
When to Use
- Tests that assert on generated UUIDs or ULIDs
- Snapshot testing where randomness breaks comparisons
- Seeding or fixtures that need deterministic identifiers
- Any scenario where non-deterministic IDs make testing harder