I'm trying to create 30 news using Seeder and Factory. But I need to create 10 news with a non-empty field value published_at
(Carbon) а для остальных случайное значение (Carbon/NULL)
In the documentation I saw such an example, it creates 5 records with the value admin (Y)
and 5 more records with the value admin (N)
User::factory()
->count(10)
->state(new Sequence(
['admin' => 'Y'],
['admin' => 'N'],
))
->create();
So far I'm using this code, but I can't figure out how to add the number of records being created with a certain parameter value published_at
. For example, 10 with Carbon and 20 with NULL.
/** ArticleSeeder */
Article::factory()
->count(30)
->state(new Sequence([
'published_at' => Factory::create()->dateTimeBetween(
now()->startOfMonth(),
now()->endOfMonth()
),
]))
->create();
CodePudding user response:
Within a sequence closure, you may access the $index property that contains the number of iterations through the sequence that have occurred thus far.
Below is the simplest logic that you can use to achieve what you want.
Article::factory()
->count(30)
->sequence(fn ($sequence) => [
'published_at' => $sequence->index < 10
? Factory::create()->dateTimeBetween(
now()->startOfMonth(),
now()->endOfMonth()
);
: null
])
->create();