How to adjust the number of objects created in Sequence (Laravel 8)
P粉043566314
P粉043566314 2023-09-04 10:08:32
0
1
574
<p>I'm trying to create 30 news items using Seeder and Factory. But I need to create 10 news items with non-null field value <code>published_at</code>(Carbon) and other news items with random values ​​(Carbon/NULL). </p> <p>In the documentation, I saw an example of this, which created 5 records with the value <code>admin (Y)</code>, and another 5 records with the value <code> admin(N)</code>. </p> <pre class="brush:php;toolbar:false;">User::factory() ->count(10) ->state(new Sequence( ['admin' => 'Y'], ['admin' => 'N'], )) ->create();</pre> <p>So far I'm using this code but I can't figure out how to add the number of records with a specific parameter value <code>published_at</code>. For example, use Carbon for 10 items and NULL for 20 items. </p> <pre class="brush:php;toolbar:false;">/**ArticleSeeder*/ Article::factory() ->count(30) ->state(new Sequence([ 'published_at' => Factory::create()->dateTimeBetween( now()->startOfMonth(), now()->endOfMonth() ), ])) ->create();</pre></p>
P粉043566314
P粉043566314

reply all(1)
P粉957723124

In a sequence closure, you have access to the $index property, which contains the number of iterations through the sequence so far.

The following is the simplest logic you can use to achieve your desired results.

Article::factory()
->count(30)
->sequence(fn ($sequence) => [
    'published_at' => $sequence->index < 10
                      ?  Factory::create()->dateTimeBetween(
                             now()->startOfMonth(),
                             now()->endOfMonth()
                         );
                      : null
])
->create();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template