M
M
maaestr02022-03-10 20:13:58
Laravel
maaestr0, 2022-03-10 20:13:58

How to write data from an array through a factory?

Hello, there is a category label in the database, and you need to somehow fill it with test, unique data. I decided to try through the factory. The data needs to be taken from the array, but how to go through the entire array and write it to the database?
Factory

public function definition()
    {   
        $category = ['art','bussines','koop','mark','psy','it','photo'];

        return [
            'title' => $category[array_rand($category,1)],
        ];
    }


Seeder
CourseCategory::factory()->count(7)->create();

The problem is that I don't know how to take a different value from the array each time.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2022-03-10
@maaestr0

Factory and seeder example with preset values

class CityFactory extends Factory
{
  protected $model = City::class;
  public function definition()
  {
    $tz = array_keys(Timezone::getData());
    return [
      'name'     => $this->faker->city,
      'timezone' => $this->faker->randomElement($tz),
      'enabled'  => true,
    ];
  }
}

use Illuminate\Database\Eloquent\Factories\Sequence;
class CitySeeder extends Seeder
{
  public function run()
  {
    $predefinedCities = array_reverse($this->getPredefinedCities());
    City::factory(CITY_COUNT)
      ->state(new Sequence(function () use (&$predefinedCities) {
        return array_pop($predefinedCities) ?? [];
      }))
      ->create();
  }

  private function getPredefinedCities()
  {
    return [
      [
        'name'         => 'Moscow',
        'timezone'     => '+0300',
        'enabled'      => true,
      ],
      [
        'name'         => 'Saint-Petersburg',
        'timezone'     => '+0300',
        'enabled'      => true,
      ],
      [
        'name'         => 'Sochi',
        'timezone'     => '+0300',
        'enabled'      => true,
      ],
    ];
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question