Search code examples
laravelphp-carbonlaravel-seeding

Seeding a MySQL table using Laravel and Carbon for next x number of days


I'm building a feature to build a playlist for next 5 years. In my table, MySQL date is my identifier and has a relation to another table which lists all podcast.

My issue is not finding enough guidance with regards to seeding a table, from today to next 5 years. What it actually means is to be able to run Laravel seed that generates a insert query for every day in next 5 years.

I'm currently using Laravel 5.8 and using Carbon. I could simply do a foreach function to generate this data however I don't think its elegant hence I'm wondering if I could use a better approach to generate dates for next 5 years? Code below can work in a loop function, i.e. create today and then add a day to keep repeating this for next 5 years but again it doesn't look like a good approach or I am wrong?

$mutable = Carbon::now();
$immutable = CarbonImmutable::now();
$modifiedMutable = $mutable->add(1, 'day');

Ideally it should return dates like

id: 1, date: 2019-06-05
id: 2, date: 2019-06-06
id: 3, date: 2019-06-07
...

Solution

  • Finally did it with a loop, it seems there is no other elegant way to do this, sharing answer for those who may consider doing what I tried to achieve.

        $startDate = new Carbon('2019-06-15');
        $endDate = new Carbon('2025-06-15');
        $all_dates = array();
        while ($startDate->lte($endDate)){
          $all_dates[] = $startDate->toDateString();
          $startDate->addDay();
        }
        dd($all_dates);