Search code examples
phplaravelphpunitlaravel-testing

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

Solution

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