Table of contents

laravel str::random() function

In this post, Let's use the Laravel Str::random() helper function with an example that will help us to generate a random string with a specified length. Sometimes we need this function when developing an application in PHP or in the Laravel framework that can able us to generate random strings for specific functionality like auto password generator.


In PHP we need to code it in a few lines like the following codes below:


function random_string($length = 10) {
    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    return $randomString;


In Laravel, they provide a helper function to shorten our work and not write this function anymore.


See the example below for how to do it.



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;

class HomeController extends Controller
     * Show the application dashboard.
     * @return \Illuminate\Contracts\Support\Renderable
    public function index()
        echo 'Generated random string 1 : ' . Str::random(10);
        echo '<br>';
        echo 'Generated random string 2 : ' . Str::random(15);
        echo '<br>';
        echo 'Generated random string 3 : ' . Str::random(30);


I hope it helps. Thank you for visiting.