Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Generate Random String using Laravel Faker?

is there any way or method to generate fake string using laravel faker ?

like in laravel we generate string upto 20 chars..

 str_random(20); 
like image 740
Vishal Avatar asked Mar 24 '18 13:03

Vishal


People also ask

How do you generate random unique strings in Laravel?

If you need to generate unique random string then you can use str_random() helper of Laravel. It is very simple and you can use easily. you can easily generate random string in laravel 6, laravel 7, laravel 8 and laravel 9 version using str helper.

What is the use of Faker in Laravel?

Faker is a PHP package that generates dummy data for testing. With Faker you can generate mass amount of testing data as you needed. Faker comes preinstalled in Laravel framework. You can also use Faker in other frameworks or your own native PHP websites.


2 Answers

Faker offers a couple of methods that let you replace placeholders in a given string with random characters:

  • lexify - takes given string and replaces ? with random letters
  • asciify - takes given string and replaces * with random ascii characters
  • numerify - takes given string and replaces # with random digits
  • bothify - combines the lexify and numerify

You could try to use one of them, depending on the requirements you have for that random string you need. asciify uses the largest set of characters as replacement so using that one makes most sense.

The following will give you a random string of 20 ascii characters:

$faker->asciify('********************') 
like image 119
jedrzej.kurylo Avatar answered Sep 30 '22 04:09

jedrzej.kurylo


Alternate for generate string without special chars.

$faker->regexify('[A-Za-z0-9]{20}') 
like image 26
Matthias Avatar answered Sep 30 '22 04:09

Matthias