Answer the question
In order to leave comments, you need to log in
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)],
];
}
CourseCategory::factory()->count(7)->create();
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question