Two Dates for One Person, and a Correction That Never Expires: Leave Balance Traps in a Laravel Model

A leave system has two kinds of facts about a person. Some are recorded by the software as it runs: when the account was created, when they accepted the invitation, when a request was approved. Others are business facts somebody has to type in: when the person was actually hired, how many days the company owes them. The trouble starts when code reads one kind while the people reading the screen assume the other.
This post walks through two places in Happy Tracker’s leave balance code where that happens, both visible to any team that moves onto the app part-way through a year. First, the balance counts from the date the membership row was created, while probation counts from the employment start date. Second, a manual balance correction is stored without a period, so it applies to every period after the one it was meant for. Neither is a crash. Both produce numbers that are internally consistent and still wrong for the person reading them. We will look at the real code, why each choice was reasonable on its own, and how to change it without moving anyone’s current balance.
Two dates on one pivot row
Membership lives on the organization_user pivot. It carries two dates that sound alike:
// organization_user pivot, as the User and Organization relations load it
->withPivot([
'role', 'hourly_rate', 'billable_rate', 'status',
'joined_at', // set by the app: when the membership row was created
'date_of_joining', // entered by HR: when the person started working here
'allow_web_clock_in',
])
joined_at is written by the application at the moment the row is created, whether that is the owner signing up or a member accepting an invitation:
// When someone accepts an invitation (InvitationController)
$invitation->organization->users()->syncWithoutDetaching([
$user->id => [
'role' => $invitation->role,
'status' => 'active',
'joined_at' => now(), // the day the ACCOUNT joined, not the hire date
],
]);
date_of_joining came later, when the product needed probation. The rule was that a new joiner cannot use certain leave types until they have been with the company for a while. The obvious column to measure that from was joined_at, and it was the wrong one. On a workspace that moved onto the app on a single day, every long-serving member had the same joined_at: the go-live date. Measuring probation from it would have put the whole company back on probation for six months. So probation got its own business date, entered by HR, and a null date means no restriction:
public function isOnProbation(Organization $organization): bool
{
$membership = $this->pivot
?? $organization->users()->where('users.id', $this->id)->first()?->pivot;
$joined = $membership?->date_of_joining;
if (! $joined) {
return false; // no start date recorded: no restriction
}
return Carbon::parse($joined)
->addMonths($organization->probationMonths()) // six by default
->isFuture();
}
That is the right model. The system timestamp records what the system did; the business date records what happened in the world; and anything that represents an employment rule reads the business date. A missing business date fails open rather than locking people out, which matters on the day the column is added and every existing row is null.
The reader that still uses the system date
The balance calculation predates that split, and it still reads joined_at:
// LeaveRequestController: the balance shown on the Time Off page
$joinedAt = $organization->users()
->where('users.id', $user->id)->first()?->pivot?->joined_at; // <- joined_at
$adjustments = $organization->leaveAdjustments()->where('user_id', $user->id)
->selectRaw('leave_type_id, SUM(delta_days) as total')
->groupBy('leave_type_id')
->pluck('total', 'leave_type_id'); // <- all time
$balance = $type->balanceFor($approvedForType, (float) ($adjustments[$type->id] ?? 0), $joinedAt);
Inside balanceFor(), the joining date does three jobs. For a yearly policy it prorates the first year’s allowance:
private function proratedAllowance(?Carbon $joined, int $year): float
{
$allowance = (float) $this->allowance_days;
if (! $joined || $joined->year !== $year) {
return $allowance;
}
// Join month counts as a full month; round to the nearest half day.
// 12 days, joined in September: 12 * (13 - 9) / 12 = 4
return round($allowance * (13 - $joined->month) / 12 * 2) / 2;
}
For a monthly policy that accumulates, it sets where accrual starts: the later of the policy’s created_at and the joining date. And for a yearly policy that carries unused days forward, it decides whether there is a last year to carry from at all; a member who joined this year carries nothing.
For a genuine new hire all three are correct. For a ten-year employee whose account was created in September, all three are wrong in the same direction: a prorated 4 days instead of 12, accrual starting in September, nothing carried. The People page now shows a “Joined on” date with the tooltip “Employment start date — probation is counted from here”, which is accurate, and which an admin can reasonably read as the date the whole leave system uses.

Why not just switch the balance to the business date?
It is a one-line change in three places, and it is the right eventual answer. Shipping it naively would still be a mistake, for the same reason date_of_joining fails open.
The moment the reader changes, every member who has a date_of_joining earlier than their joined_at gets a different balance: a larger first-year allowance, an earlier accrual start, possibly a carry-over that did not exist yesterday. Some admins will already have corrected those balances by hand, which brings us to the second problem. Their corrections would now be double-counted. A balance that was right this morning would be wrong this afternoon, and nobody would have touched it.
The safe sequence is the usual one for changing what a stored number means:
- Compute both versions side by side for every member, without showing the new one.
- List the members whose balance would change, with the existing adjustments next to them.
- Decide per workspace, with the admin, whether those adjustments were compensating for the old date. If so, they are retired as part of the switch.
- Switch the reader, and record in the audit log that balances were recalculated and why.
Until that happens, the honest product behaviour is to say clearly that balances count from the day the account joined, and to make first-year corrections easy and safe. Which leads to adjustments.
A correction with no period
Owners and admins can correct a balance by a number of days, up or down. The endpoint is small and careful: it checks the person and the leave type belong to the caller’s organization, refuses zero, records who made the change, writes the audit log and notifies the member.
$data = $request->validate([
'user_id' => ['required', 'integer'],
'leave_type_id' => ['required', 'integer'],
'delta_days' => ['required', 'numeric', 'between:-365,365', 'not_in:0'],
'note' => ['sometimes', 'nullable', 'string', 'max:255'],
]);
// no period, no effective date: the row applies to whatever period is being computed
What it does not record is when the correction applies. And the read side, shown earlier, sums every adjustment ever made for the person and type, with no date filter. That total is then fed into whichever period is being computed. Here are the lines in balanceFor() where it lands:
// balanceFor(), trimmed to the lines where $adjustment is used
if ($this->accrual_type === 'unlimited') {
return ['entitled' => null, /* ... */]; // adjustment ignored
}
if ($this->accrual_type === 'monthly') {
if ($this->monthly_carryover === 'capped') {
$entitled = $rate + $adjustment; // added to EVERY month
// ...
}
if ($this->yearly_carryover === 'expire') {
$entitled = $rate * $monthsThisYear + $adjustment; // added to EVERY year
// ...
}
$entitled = $rate * $monthsSinceStart + $adjustment; // one running balance: correct
// ...
}
$entitled = $base + $carried + $adjustment; // yearly: added to EVERY year
Walk each branch with a +8 correction made in September:
- Monthly, accumulating, carries across years. One continuous balance since the person started. A one-off +8 is meant to stay forever. Correct.
- Unlimited. No entitlement to correct; the adjustment is ignored. Harmless.
- Yearly. In January the base resets to the full allowance and last year’s unused days are carried. The +8 is added again. The person who was owed 8 extra days once is now owed 8 extra days every year.
- Monthly, accumulating, resets each January. Same as yearly: the correction comes back every year.
- Monthly, capped. The entitlement is this month’s grant only, and the +8 is added to it. Every month.
The model treats an adjustment as a delta on a running total. Only one of the four policy shapes actually is a running total. The others are periodic entitlements, and a delta without a period is applied to every period.
There is no delete endpoint, which is a good thing for an audit trail: you undo a correction by adding its opposite. But it means the workaround for a periodic policy is a calendar reminder. Someone has to add −8 on the first working day of January, and for capped monthly policies, the following month.

Giving an adjustment a period, without moving any balance
The fix follows the same pattern as date_of_joining: add the missing fact as a nullable column, and make null mean exactly what every existing row means today.
// Illustrative, not shipped: give an adjustment the period it belongs to.
Schema::table('leave_adjustments', function (Blueprint $table) {
// NULL = "applies to every period" — exactly what existing rows mean today,
// so adding the column changes no balance on the way in.
$table->unsignedSmallInteger('applies_year')->nullable()->after('delta_days');
$table->unsignedTinyInteger('applies_month')->nullable()->after('applies_year');
});
Existing rows keep applies_year = NULL, which the read side treats as “applies to every period”. That is today’s behaviour, so the migration changes no balance. New rows written through the UI get the period the admin is looking at when they make the correction. The form can default it to the current year, or the current month for a capped policy, and let the admin choose “permanent” explicitly.
The read side then sums only what belongs to the period being computed:
// Illustrative: sum only the adjustments that belong to the period being shown.
private function adjustmentFor(LeaveType $type, int $userId, Carbon $now): float
{
$q = $type->adjustments()->where('user_id', $userId);
$q->where(function ($q) use ($type, $now) {
$q->whereNull('applies_year'); // legacy / permanent rows
if ($type->accrual_type === 'monthly' && $type->monthly_carryover === 'capped') {
$q->orWhere(fn ($q) => $q->where('applies_year', $now->year)
->where('applies_month', $now->month));
} elseif ($type->resetsYearly()) {
$q->orWhere('applies_year', $now->year);
} else {
$q->orWhereNotNull('applies_year'); // running balance: all count
}
});
return (float) $q->sum('delta_days');
}
Two details matter.
The running-balance branch still counts everything. For a policy that carries across years, a correction made in 2026 must still count in 2027, whatever period it was stamped with. Scoping is a property of the policy shape, not of the adjustment alone, so the decision belongs next to the policy logic that already knows which shape it is.
Carry-over has to see the same scoped total. A yearly policy that carries unused days computes last year’s leftover from last year’s base and last year’s usage. If a first-year correction is now scoped to last year, it should be part of last year’s base when the leftover is calculated. Otherwise the 8 days the person was owed and did not take vanish at the year boundary instead of carrying, which is the opposite mistake. The simplest way to keep these consistent is to compute a period’s entitlement through one function, and have the carry-over call that same function for the previous period instead of re-deriving it.
Year, month, or a date range?
The illustrative migration stores a year and an optional month. It is worth being explicit about why that, rather than an effective date range, which looks more general.
A range such as effective_from and effective_to forces every reader to decide what “applies” means when the range only partly overlaps the period being computed. Does a correction effective from 15 March count for a monthly grant in March, or only from April? For a yearly entitlement, does a range of July to June split across two years? Each answer is defensible, and each reader would have to implement it the same way to stay consistent. The policy shapes in this model are already periodic. A yearly policy has years, and a capped monthly policy has months. So stamping a correction with the period it belongs to matches the data to the calculation, and there is nothing to interpret.
The one shape that has no period, the running balance, simply ignores the stamp. That asymmetry belongs in code, next to the policy, rather than in the admin’s head.
It also keeps the form simple. The admin is already looking at a specific balance for a specific period when they press the button. Defaulting the stamp to that period means the common case, “fix this year’s figure”, needs no extra input. The rare case, a correction that should stay forever, is a deliberate choice with its own label.
Legacy rows: do not guess their period
Once the column exists, it is tempting to backfill it. Every existing adjustment has a created_at, so stamping each with the year it was made looks like a free improvement. It is not.
An adjustment made in December might be a correction to that year, or an opening balance meant to carry into the next one. A +8 made in September on a carry-across-years policy is meant to be permanent, and so is one made for the same reason on a yearly policy by an admin who did not know it would repeat. The row does not record intent, and the note field is free text. A backfill that guesses wrong silently removes days from someone’s balance in January, which is worse than the bug being fixed, because now nobody can see why.
Leave legacy rows as null, meaning permanent, which is exactly how they behave today. Then show admins a list of their existing adjustments on periodic policies, with the note and the date, and let them stamp the ones they meant as temporary. A one-time review per workspace is a few minutes of work. A wrong backfill is a support conversation per affected employee.
What the screen should say in the meantime
Code changes take time to ship. The cheapest improvement is copy, and it removes most of the risk on its own:
- Next to “Joined on” on the People page, say what it does not do: it sets probation and does not change leave balances, which count from the day the person joined the workspace.
- In the Adjust balance window, say that an adjustment applies to every period of a resetting policy, and suggest noting when it should be reversed.
- On a capped monthly policy, warn before saving an adjustment at all, because the effect, the same amount every month, is almost never what the admin intends.
None of that needs a migration, and all of it matches what the code does today. Accurate copy about a limitation is better than a feature the user misreads.
Testing it the way it breaks
Both bugs are invisible in a test that runs on a single date, because both only show up when the calendar moves. The useful tests freeze time, make the correction, then move the clock across the boundary:
// Illustrative Pest test: a first-year correction must not survive into January.
it('does not carry a first-year correction into the next year', function () {
Carbon::setTestNow('2026-09-20');
[$org, $member, $annual] = workspaceWithYearlyPolicy(days: 12); // member joins today
expect(balance($member, $annual)['entitled'])->toBe(4.0); // 12 * 4/12
adjust($member, $annual, +8, appliesYear: 2026);
expect(balance($member, $annual)['entitled'])->toBe(12.0);
Carbon::setTestNow('2027-01-05');
// full year now, plus whatever carried, but NOT the 2026 correction
expect(balance($member, $annual)['entitled'])
->toBe(12.0 + carriedFrom2026($member, $annual));
});
Write one of these per policy shape, plus one that runs the migration against a copy of real data and asserts no balance changed. That last test is the one that lets you ship on a weekday afternoon.
What to take from it
- Keep system timestamps and business dates in separate columns, and name them so the difference is obvious.
account_joined_atandemployment_started_onwould have prevented the confusion;joined_atanddate_of_joininginvite it. - When you add a business date, audit every reader of the old system date, not just the feature you are building. Probation moved to the right date; balances did not, and the UI now implies that they did.
- A delta needs the period it applies to, unless the thing it modifies is a true running total. Ask which shape each consumer has before choosing one storage model for all of them.
- Add missing facts as nullable columns whose null means the current behaviour. It turns a risky data migration into a no-op deploy followed by a product decision.
- Test across boundaries: month end, year end, the day a policy was created. That is where periodic logic and running totals disagree.
For anyone moving their own team onto Happy Tracker mid-year, the practical version of this, with the switch-over checklist, is on our sister blog: why first-year leave looks short and how to correct it safely.
Happy Tracker is our time tracking, leave and attendance system for service businesses, free for up to five users. See how it works.



