How to increment date by one month in laravel?
Asked Answered
A

2

1

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

Atp answered 31/5, 2022 at 5:0 Comment(1)
See my answer to this question: https://mcmap.net/q/173215/-increment-date-by-one-month/…Rooky
T
1

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');
}
Thriller answered 31/5, 2022 at 5:21 Comment(2)
not working sir. @Ross_102Atp
@swapnilmane, edited my answer, is it working now?Thriller
H
1
$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.

Hebdomad answered 31/5, 2022 at 6:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.