rahman j89
rahman j89

Reputation: 85

How can I make fake records in a way that some of them have specific values in laravel?

I need to make some fake records in laravel testing in a way that some of them have specific values.

for example I need to create 20 fake records of countries name and want to name the two records "USA" and "UK" and other values is not important.

If I use this code all records name will be same:

$country = Country::factory()->count(20)->create(['name'=> 'USA']);

Upvotes: 0

Views: 1047

Answers (2)

damask
damask

Reputation: 555

You can do it like this

$country = Country::factory()
    ->count(20)
    ->sequence(new Sequence(
        function($sequence) { 
            return $index === 0 ? 
            ['name' => 'UK'] : 
                $index === 1 ? 
                ['name' => 'USA'] : 
                ['name' => $this->faker->word()]; 
        }
    ))
    ->create();

That way, if the sequence is in its first iteration, name will be set to 'UK', second iteration will be 'USA', and after that a random word.

Upvotes: 0

gguney
gguney

Reputation: 2663

Why just use 2 lines?

Country::factory()->count(10)->create(['name'=> 'USA']);
Country::factory()->count(10)->create();

Or you can put into your factory like:

/**
 * Define the model's default state.
 *
 * @return array<string, mixed>
 */
public function definition()
{
    return [
        'name' => $this->faker->boolean ? $this->faker->randomElement(['USA', 'UK']) : null,

Upvotes: 0

Related Questions