Skip to content
Advertisement

How do I make a factory that creates random titles without a dot at the end?

I am working on a Laravel 8 blogging application. I need a large numer of articles in order to test the pagination.

For this purpose, I have made this factory:

class ArticleFactory extends Factory
{ 
 /**
 * The name of the factory's corresponding model.
 *
 * @var string
 */
protected $model = Article::class;

/**
 * Define the model's default state.
 *
 * @return array
 */
public function definition()
{
    
    $title = $this->faker->sentence(2);

    return [
          'user_id' => $this->faker->randomElement([1, 2]),
          'category_id' => 1,
          'title' => $title,
          'slug' => Str::slug($title, '-'),
          'short_description' => $this->faker->paragraph(1),
          'content' => $this->faker->paragraph(5),
          'featured' => 0,
          'image' => 'default.jpg',
    ];
  }
}

The problem

Unfortunately, the title column in the articles table is populated with sentences that have a dot at the end. Titles are not supposed to end with a dot.

How can I fix this?

Advertisement

Answer

Instead of $this->faker->sentence(2); you could use $this->faker->words(3, true); where you can replace the 3 with the amount of words you want. true is there so it returns a string and not an array

It adds a dot because you use ->sentence() and sentences, normally, have a period at the end. Whereas words typically do not have a period at the end.

You can ofcourse also provide a random amount of words by using rand(). Say you want a title to be between 5 and 15 words, you can use $this->faker->words(rand(5, 15), true);

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement