Home > Blockchain >  How to increment date by one month in laravel?
How to increment date by one month in laravel?

Time:05-31

I am storing data in the database where I want to increment the date by one month. I have given the code below. The first row is inserted successfully but after that, data didn't get inserted correctly.

 $startMonth = $wallet_master->created_at;
      // 31-5-2022
      $endMonth = $wallet_master->created_at->addDays(30);
      //30-6-2022

      for ($i = 0; $i < $wallet_package->wallet_duration; $i  ) {

        $data = [   
          'start_date' => $startMonth,
          'end_date' =>   $endMonth,
          ];

        DB::table('wallet_table')->insert($data);
        $startMonth = $endMonth->addDays(1);
        $endMonth =  $startMonth->addDays(30);

CodePudding user response:

You have the same Carbon instance all the time, so you need to store the formatted start and end dates:

$date = $wallet_master->created_at;
$startMonth = $date->format('d-m-Y');
// 31-5-2022
$endMonth = $date->addDays(30)->format('d-m-Y');
//30-6-2022

for ($i = 0; $i < $wallet_package->wallet_duration; $i  ) {

    $data = [   
         'start_date' => $startMonth,
         'end_date' =>   $endMonth,
    ];

    DB::table('wallet_table')->insert($data);
    $startMonth = $date->addDays(1)->format('d-m-Y');
    $endMonth =  $date->addDays(30)->format('d-m-Y');
}

CodePudding user response:

$date = $wallet_master->created_at;

for ($i = 0; $i < $wallet_package->wallet_duration; $i  ) {
    $startMonth = $date->copy()->addMonthsNoOverflow($i)->format('d-m-Y');
    $endMonth =  $date->copy()->addMonthsNoOverflow($i   1)->subDay()->format('d-m-Y');

    DB::table('wallet_table')->insert([   
         'start_date' => $startMonth,
         'end_date' =>   $endMonth,
    ]);
}

Note: no need for ->copy() if you use CarbonImmutable.

  • Related