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).

Share:
46,553
Vishal
Author by

Vishal

Updated on July 09, 2022

Comments

  • Vishal
    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
    Sebastian Viereck over 5 years
    you can produce a string with 20 times a * with str_repeat('*', 20)
  • phoenixstudio
    phoenixstudio about 3 years
    Please explain your answer
  • Jiechao Wang
    Jiechao Wang about 3 years
    $faker->text(50);
  • francisco
    francisco almost 3 years
    You can use like [A-z] to simplify the [A-Za-z] in your regex.
  • DevAntoine
    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
    Steve Moretz over 2 years
    This is wrong, it makes a sentence with spaces in the middle of words.