How to Generate Random String using Laravel Faker?
46,553
Solution 1
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('********************')
Solution 2
Alternate for generate string without special chars.
$faker->regexify('[A-Za-z0-9]{20}')
Solution 3
$faker->text($maxNbChars = 50);
Solution 4
uze Faker\Provider\en_US\Text
<?php
realText($maxNbChars = 200, $indexSize = 2) // "And yet I wish you could manage it?) 'And what are they made of?' Alice asked in a shrill, passionate voice. 'Would YOU like cats if you were never even spoke to Time!' 'Perhaps not,' Alice replied."
Solution 5
$faker->text()
// generates 50 char by default: "Aut quo omnis placeat eos omnis eos."
$faker->text(10);
// generates 10 char by default: "Labore."
All texts seems to be one or more latin pseudo-sentences with spaces and always a dot in the end (of each sentence).
Author by
Vishal
Updated on July 09, 2022Comments
-
Vishal almost 2 years
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);
-
Sebastian Viereck over 5 yearsyou can produce a string with 20 times a * with str_repeat('*', 20)
-
phoenixstudio about 3 yearsPlease explain your answer
-
Jiechao Wang about 3 years$faker->text(50);
-
francisco almost 3 yearsYou can use like [A-z] to simplify the [A-Za-z] in your regex.
-
DevAntoine almost 3 years@francisco these are not the same. A-z is a character range of ascii 65 to 122. You should use /[A-Za-z]/ or /[a-z]/i, unless you wish to include these characters: [ \ ] ^ _ `
-
Steve Moretz over 2 yearsThis is wrong, it makes a sentence with spaces in the middle of words.