Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jrdavidson's avatar

Creating Events For Certain Days of the week in the past

I'm trying to seed a database table with very specific data for dates of events for my application.

I am currently creating 50 events that span random dates for the current time going back 10 years, however, what I am wanting to do is only have the dates taking place every Monday and Thursday of every week and also have it take place on the last Sunday of every month. What would I have to do to accomplish this? I've looked at Carbon and like how extensive it is but not sure how to work with this specific type of dates. The date was created in my model factory.

for($i = 1; $i <= 50; $i++) {
    $event = factory(Event::class)->create(['name' => 'Event '.$i, 'slug' => 'event'.$i]);
}
0 likes
3 replies
jrdavidson's avatar

@bastman69 Yes but you can't get the iteration to put it into the strings like I am. So I have to loop unless you know something I dont.

1 like
willvincent's avatar
Level 54

This will spit out Mondays, Thursdays and last sundays of each month for the past year, should be easy enough for you to change into a db seed:

It's not pretty, but it should do the job.

$month = \Carbon\Carbon::now()->month;
foreach(range(1,51) as $w) {
  $mon = \Carbon\Carbon::parse('monday')->subWeeks($w);
  $thur = \Carbon\Carbon::parse('thursday')->subWeeks($w);

  print 'MON: '. $mon->format('Y-m-d') . "\n";
  print 'THUR: '. $thur->format('Y-m-d') . "\n";
  if ($thur->month != $month) {
    $sunday = \Carbon\Carbon::parse('last sunday of ' . $thur->copy()->format('M Y'));
    print 'SUNDAY: ' . $sunday->format('Y-m-d') . "\n";
    $month = $thur->month;
  }
}

Copy paste into tinker to see for yourself.

1 like

Please or to participate in this conversation.