Home > Mobile >  Laravel factory, my data is from an array, not random
Laravel factory, my data is from an array, not random

Time:05-29

Tell me how to add not random data, but certain ones in factories. For example, I want to create 3 factories and fill the fields with all the values from the array.

Here I am creating 3 factories with random id from database. And I need to create 3 factories to get basic_section_id = 1, basic_section_id = 2, basic_section_id = 3.... And not random id in each factory. Tell me please.

class BasicCardFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'basic_section_id' => BasicSection::all()->random()->id
        ];
    }
}

class BasicSectionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $basicSections = BasicSection::factory(3)->create();
    }
}

CodePudding user response:

If you would like to override some of the default values of your models, you may pass an array of values to the make method. Only the specified attributes will be replaced while the rest of the attributes remain set to their default values as specified by the factory: (Laravel Docu - https://laravel.com/docs/9.x/database-testing#overriding-attributes)

 $user = User::factory()->make([
     'name' => 'Abigail Otwell',
 ]);

In your case would that look something like:


class BasicSectionSeederFactory extends Factory{
   public function definition()
   {
      return [
         'property1' => $this->fake->name(),
         'notRandom' => "foobar",
         //...
      ];
   }
}


 $seeder = BasicSectionSeeder::factory()->make( [
  //your properties go here ...
 ]);

You need to "make" models with the factory. That's the clue.

Checkout the whole docs a bit, to get all the conventions needed as well: https://laravel.com/docs/9.x/database-testing#factory-and-model-discovery-conventions

CodePudding user response:

If you are using laravel 8 maybe the Sequence class for factories could simplify your code a little. In your case an example could be:

class BasicSectionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $basicSections = BasicSection::factory()
                                     ->count(3)
                                     ->sequence(fn ($sequence) => ['basic_section_id' => $sequence->index   1])
                                     ->create();
    }
}

For more info you can check official doc: https://laravel.com/docs/9.x/database-testing#sequences

  • Related