Jakyy B
Jakyy B

Reputation: 55

Very strange error with Carbon and Laravel

I'm using Laravel for one of my project. Everything is just fine, but I can't solve a strange error.

  1. I'm sending duration in years from my front end (Vuejs).
  2. If client is on any active plan then plan start should be the current plan end date else set to now().
  3. Add years in start time and set as plan end.

Now when I do this in actual code, I see same start and end date generated according to plan end.

$start = Carbon::parse($client->plan_end) ?: Carbon::now();

$end = $start->addYears($request->planDetails['duration']);

return response([
  'start' => $start,
  'end' => $end,
]);

This is plan_end timestamp in database -- 2022-05-09 09:15:19

This is response I receive.

{
   "start" : "2024-05-09T07:15:19.000000Z",
   "end" : "2024-05-09T07:15:19.000000Z"
}

Upvotes: 4

Views: 545

Answers (2)

KyleK
KyleK

Reputation: 5131

Using ->copy() is fine, but using CarbonImmutable as default is likely better as it will avoid similar pain to happen again:

$start = CarbonImmutable::parse($client->plan_end) ?: CarbonImmutable::now();

$end = $start->addYears($request->planDetails['duration']);

return response([
  'start' => $start,
  'end' => $end,
]);

Upvotes: 1

Jacob Brassington
Jacob Brassington

Reputation: 257

So carbon is mutable which means that when you do ->addYears() it will alter the original start date time. You can use the ->copy() function before adding the years so it would look like this.

$end = $start->copy()->addYears($request->planDetails['duration']);

Upvotes: 5

Related Questions