You can use :

sha1(time())

Explanation: sha1 is hash function, and most important characteristic of hash function is that they never produce the same hash of different string, so as time() is always unique in theory sha1(time()) will always give you unique string with fixed width.

EDITED:

You can use you function but before giving token you can connect to database and check if token exists, if exists generate new token, if not exists give hin this token. This mechanism will give you unique tokens.

Answer from fico7489 on Stack Overflow
๐ŸŒ
Laravel Daily
laraveldaily.com โ€บ post โ€บ generate-random-strings-laravel-helper-methods
Generate Random Strings with Laravel: Helper Methods
Another option is to combine random_bytes() and bin2hex() PHP functions to generate a 20 character string. ... For a random number, the mt_rand() could be used. The default minimum value is zero, and the maximum value is generated by mt_getrandmax.
Discussions

Is it possible to generate unique and random string easily in Laravel 4? | Laravel.io
The Laravel portal for problem solving, knowledge sharing and community building. More on laravel.io
๐ŸŒ laravel.io
string - Laravel str_random() or custom function? - Stack Overflow
As random_bytes became available in PHP 7 Laravel slowly shifted to that function and uses that one only without any fallback. ramsey/uuid is the default UUID library in Laravel. By looking at the code we can find out the default random generator is RandomBytesGenerator which uses random_bytes. More on stackoverflow.com
๐ŸŒ stackoverflow.com
php - random string generator in laravel - Stack Overflow
You are generating random string outside of the loop. Therefore in every loop, you are passing the same (the only generated) one to info() method. More on stackoverflow.com
๐ŸŒ stackoverflow.com
October 25, 2019
PHP random string generator - Stack Overflow
I'm trying to create a randomized string in PHP, and I get absolutely no output with this: More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
DEV Community
dev.to โ€บ codeanddeploy โ€บ generate-random-string-in-php-j9e
Generate Random String in PHP - DEV Community
May 1, 2023 - Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW! Now you have already how to generate random strings in PHP. It's time to implement it in your project. I hope this tutorial can help you.
๐ŸŒ
Medium
medium.com โ€บ @randomstr โ€บ random-string-generation-in-php-and-its-frameworks-bb4b2f1bbce6
Random String Generation in PHP and Its Frameworks | by Random STR | Medium
December 1, 2023 - Laravelโ€™s Str::random function is a convenient and secure way to generate random strings for various applications. In Symfony, another widely-used PHP framework, you can use the Uuid component to generate a random string:
๐ŸŒ
Stillat
stillat.com โ€บ blog โ€บ 2017 โ€บ 12 โ€บ 06 โ€บ laravel-5-string-helpers-generating-random-strings
Laravel 5 String Helpers: Generating Random Strings ยป Stillat
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.
๐ŸŒ
Medium
medium.com โ€บ @harrisrafto โ€บ enhance-your-string-manipulation-with-str-random-in-laravel-ea3a3ac29f49
Enhance your string manipulation with Str::random() in Laravel | by Harris Raftopoulos | Medium
July 8, 2024 - Letโ€™s dive into how Str::random() can enhance your string manipulation in Laravel projects. The Str::random() function is part of the Illuminate\Support\Str class. It generates a random string of the specified length using a pool of alphanumeric ...
Find elsewhere
๐ŸŒ
Code And Deploy
codeanddeploy.com โ€บ home โ€บ blog โ€บ php โ€บ generate random string in php
Generate Random String in PHP - Code And Deploy
August 6, 2021 - <?php function randomString($length = 10) { // Set the chars $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // Count the total chars $totalChars = strlen($chars); // Get the total repeat $totalRepeat = ceil($length...
๐ŸŒ
Laravel.io
laravel.io โ€บ forum โ€บ 08-29-2014-is-it-possible-to-generate-unique-and-random-string-easily-in-laravel-4
Is it possible to generate unique and random string easily in Laravel 4? | Laravel.io
0 ยท ivermoller replied 11 years ago ยท Or ยท $myStr = str_random(60); The example shown is with string length of 60 characters. However don't think that this string necessarily is unique the probability of it not being unique is quite small though.
๐ŸŒ
Weblance-online
weblance-online.com โ€บ home โ€บ website โ€บ laravel โ€บ using laravel helper methods to generate random strings
Using Laravel Helper Methods To Generate Random Strings - Weblance Online Solutions
June 19, 2024 - The str_random() method in Laravel is a simple and effective way to generate random strings. This method takes a single parameter, which specifies the length of the random string to be generated.
๐ŸŒ
Code And Deploy
codeanddeploy.com โ€บ home โ€บ blog โ€บ laravel โ€บ laravel str::random() helper function example
Laravel Str::random() Helper Function Example
May 28, 2022 - 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. <?php 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 : ' .
Top answer
1 of 7
87

str_random (Str::random()) tries to use openssl_random_pseudo_bytes which is a pseudo random number generator optimized for cryptography, not uniqueness. If openssl_random_pseudo_bytes is not available, it falls back to quickRandom():

public static function quickRandom($length = 16)
{
    $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

    return substr(str_shuffle(str_repeat($pool, 5)), 0, $length);
}

In my opinion quickRandom code is not reliable for uniqueness nor cryptography.

Yes, having openssl_random_pseudo_bytes and using 32 bytes is almost impossible to see a collision, but it's still possible. If you want to make sure your strings/numbers will be unique (99.99%), you better use a UUID function. This is what I normally use:

/**
 * 
 * Generate v4 UUID
 * 
 * Version 4 UUIDs are pseudo-random.
 */
public static function v4() 
{
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',

    // 32 bits for "time_low"
    mt_rand(0, 0xffff), mt_rand(0, 0xffff),

    // 16 bits for "time_mid"
    mt_rand(0, 0xffff),

    // 16 bits for "time_hi_and_version",
    // four most significant bits holds version number 4
    mt_rand(0, 0x0fff) | 0x4000,

    // 16 bits, 8 bits for "clk_seq_hi_res",
    // 8 bits for "clk_seq_low",
    // two most significant bits holds zero and one for variant DCE1.1
    mt_rand(0, 0x3fff) | 0x8000,

    // 48 bits for "node"
    mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
}

It generates a VALID RFC 4211 COMPLIANT version 4 UUID.

Check this: https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions

2 of 7
75

you can use this

use Illuminate\Support\Str;

$random = Str::random(40);
Top answer
1 of 16
1696

To answer this question specifically, two problems:

  1. $randstring is not in scope when you echo it.
  2. The characters are not getting concatenated together in the loop.

Here's a code snippet with the corrections:

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';

    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[random_int(0, $charactersLength - 1)];
    }

    return $randomString;
}

Output the random string with the call below:

// Echo the random string.
echo generateRandomString();

// Optionally, you can give it a desired string length.
echo generateRandomString(64);

Please note that previous version of this answer used rand() instead of random_int() and therefore generated predictable random strings. So it was changed to be more secure, following advice from this answer.

2 of 16
443

Note: str_shuffle() internally uses rand(), which is unsuitable for cryptography purposes (e.g. generating random passwords). You want a secure random number generator instead. It also doesn't allow characters to repeat.

One more way.

UPDATED (now this generates any length of string):

function generateRandomString($length = 10) {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

echo  generateRandomString();  // OR: generateRandomString(24)

That's it. :)

๐ŸŒ
GitHub
github.com โ€บ webcraft โ€บ laravel-random
GitHub - webcraft/laravel-random: Laravel 5 wrapper around ircmaxell/RandomLib
It lets you generate random numbers and strings, both for general usage and for usages in security contexts, such as tokens or strong cryptograhic keys. ... [If you are using Laravel 5.5 with auto-discovery, you can skip this step] Then, add the service provider to your config/app.php file:
Starred by 10 users
Forked by 2 users
Languages ย  PHP 100.0% | PHP 100.0%
๐ŸŒ
Laravel
laravel.com โ€บ docs โ€บ 11.x โ€บ strings
Strings - Laravel 11.x - The PHP Framework For Web Artisans
If the substring does not exist ... $position = Str::position('Hello, World!', 'W'); // 7 ยท The Str::random method generates a random string of the specified length....
๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ function.rand.php
PHP: rand - Manual
If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15). ... This function does not generate cryptographically secure values, and must not be used for cryptographic purposes, or purposes that require returned values to be unguessable.