How to create X characters random string in Laravel

Laravel framework provides us with many built-in packages that aid in certain functionalities. Let’s. learn how to create X characters random string in Laravel.

We can use the string helper functions for this. Some examples are str_limit, str_plural, str_finish, str_singular. This helps generate a unique random string. Suppose the str_random() helper function of Laravel can easily create a random string.

str_random() function

The str_random() function will take in a numeric argument and returns a unique string. Consider the example below.

X Characters Random String Example

In this example, we will use the str_random() helper function to generate a random string with a specific length. This function can work in applications like generating a password with defined characters and alphabets. Consider the code snippet below without a helper function in php.

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

Now let’s go through a code while using the Laravel helper function.

<?php

namespace App\Http\Controllers;

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

class HomeController extends Controller
{
    public function index()
    {
        echo 'Generated random string 1 : ' . Str::random(6);
    }
}

Check the difference! How incredibly short and simple it makes the code. A 4-6 lines code in a single line by using a few imports. The str_random() function is greatly helpful in huge applications while easing the character generation process.

The str_random() function works with an effective algorithm that comes up with X characters random string having the specified (X) number of characters as set by a user.