Why the Str::ulid() method in Laravel always return the ulid in uppercase?

717 Views Asked by At

I am using Laravel and when I get the result of this method:

return (string) Str::ulid();

it returns this:

01H32R5Z0NDY1WRYWKWT20ZQYM

I was trying the get something like this:

01gd6r360bp37zj17nxb55yv40

I would like it to return a mix of uppercase and lowercase characters, not only uppercase, this is weird because in the laravel documentacion it shows a mix of uppercase and lowercase characteres

1

There are 1 best solutions below

0
Alexey On

ULID doesn't support mix case. You can use a function which can transform any case to mix case:

function toMixCase(string $string): string
{
    $result = strtolower($string);
    $length = strlen($result);
    $numberOrUpperSymbols = random_int(0, $length - 1);

    for ($i = 0; $i < $numberOrUpperSymbols; $i++) {
        $randomIndex = random_int(0, $length - 1);
        $result[$randomIndex] = strtoupper($result[$randomIndex]);
    }

    return $result;
}

$ulid = toMixCase(Str::ulid()->toString());

Or you just can use Str::random(26). It's not the ULID but in this case you will get a random string with mix case by default