Home  >  Q&A  >  body text

How to adjust the number of objects created in Sequence (Laravel 8)

<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粉043566314P粉043566314434 days ago521

reply all(1)I'll reply

  • P粉957723124

    P粉9577231242023-09-05 00:50:01

    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();

    reply
    0
  • Cancelreply