PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, April 19, 2022

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

 April 19, 2022     laravel, laravel-8, php     No comments   

Issue

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?

Solution

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



Answered By - geertjanknapen
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing