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

theUnforgiven's avatar

Date incrementing based on given date

Hi all,

I hope everyone is well & healthy.

I have a small issue, I can't seem to get my around.

Just bashing this out in Tinkerwell for quickness, but it's doing as I want.

$duration = 12;
$start = '2020-06-05';
$end = '2021-06-04';
$diff_in_months = diffInMonths($start,$end);
$date = Carbon\Carbon::now()->addMonth();


for ($i = 0; $i <= $duration; $i++) {
    return Commitment::create([
        'user_id' => 270,
        'tenancy_id' => 108,
        'dates' => $date // This is what I'm struggling with...
    ]);
}

So for each records it should be 12 records or whatever is within the duration, but the dates attribute in the create method should be from the start date and increment the months to the end date. So how would one achieve this so there would be 12 records in the db starting from 2020-06-05 then next record would be 2020-07-05 then 2020-08-05 and so on until the end date of 2021-06-04 in this example.

Thanks in advance and I hope one of you lovely people can help me...

0 likes
4 replies
MichalOravec's avatar
Level 75
use Carbon\Carbon;

$start = Carbon::parse('2020-06-05');

$end = Carbon::parse('2021-06-04');

$duration = $start->diffInMonths($end);

for ($i = 0; $i <= $duration; $i++) {
    Commitment::create([
        'user_id' => 270,
        'tenancy_id' => 108,
        'dates' => $i == $duration ? $end->toDateString() : $start->addMonths($i)->toDateString()
    ]);
}
1 like
theUnforgiven's avatar

Although this seemed right at the time, it's actually not:

If I specify the start date as 2020-07-01 I want that to go in the loop also, and then finish the loop when it hits the end date given, say in 6 months time..

here's what I extracted from the db as JSON, so right in the sense, but would need to also add the start date one too.

[
  {
    "id": 127,
    "user_id": 129,
    "tenancy_id": 59,
    "dates": "2020-08-01 00:00:00",
    "month": 0
  },
  {
    "id": 128,
    "user_id": 129,
    "tenancy_id": 59,
    "dates": "2020-09-01 00:00:00",
    "month": 0
  },
  {
    "id": 129,
    "user_id": 129,
    "tenancy_id": 59,
    "dates": "2020-10-01 00:00:00",
    "month": 0
  },
  {
    "id": 130,
    "user_id": 129,
    "tenancy_id": 59,
    "dates": "2020-11-01 00:00:00",
    "month": 0
  },
  {
    "id": 131,
    "user_id": 129,
    "tenancy_id": 59,
    "dates": "2020-12-01 00:00:00",
    "month": 0
  }
]
theUnforgiven's avatar

Does anyone have any more suggestions on how I achieve such task please :)

Please or to participate in this conversation.