Laravel 5

Laravel 5 String Helpers: Generating Random Strings


John Koster

Published on December 6, 2017

The random helper method generates a random string of the specified $length. This method internally uses the OpenSSL function openssl_random_pseudo_bytes, and therefore requires the OpenSSL extension to be installed and configured.


The signature of the random method is:

1public static function random(
2 $length = 16
3 );

Example Use

It should also be noted that the random method remove the following characters:


A RuntimeException will be thrown if a call is made to random without the OpenSSL extension installed.

The following examples show sample output. Because the intention of the random method is to generate a random string, any output you get will likely be different:

1use Illuminate\Support\Str;
3// XHJtXFOa5Jt8B48z
4echo Str::random();
6// z50fdgeBrmoJRBh7
7echo Str::random();
9// 2bXJNUcZVdtZfUUzbEgfvvaawOCfOgvK
10echo Str::random(32);

Global str_random Helper Function

The str_random function is a shortcut to calling Str::random. This function is declared in the global namespace.

Explore The Blog

Laravel 4: Rendering a View to a String

Published on October 31, 2013

Read More

Laravel Collection Public API: keys

Published on November 29, 2016

Read More