Generate Random Unique String in Laravel


How to Generate Random Unique String in Laravel

There are different methods are available in Laravel and PHP to generate random strings. In this tutorial, you are going to learn how to generate unique, random string in Laravel.

1. Random Unique String with Str::random()

Following is the basic syntax for Str::random() Method:

Str::random($length)

Where $length is the length of the random unique string and the default value for length is 16.

For Example,

use Illuminate\Support\Str;
 
Str::random(10)

The output should be:

ru94frh4fh

2. random() Helper:

You can generate a random string with random() helper. Following is the basic syntax for str_random helper:

random($length)

Where you can pass the length of the string as an argument to the method.

Example:

random(10)

The output should be:

5iuy95ghri

Conclusion

You have successfully learned how to Generate Random Unique String in Laravel. If you have any queries regarding this please don’t forget to comment below.