Reputation: 1983
I have a payments table where I keep track of certain payments. Let's say I have a start date, which can be any date. Payments will have to be made each month.
For example, I want to track if a payment is due 5 days before it needs to be made. This will be checked on a daily basis. For this I use the following method:
public function isDue()
{
for ($i = 0; $i <= $this->months; $i++) {
if (Carbon::now()->format('Y-m-d') >= Carbon::createFromFormat('Y-m-d', $this->start)->addMonthsNoOverflow($i)->subDays(5)->format('Y-m-d')
&&
Carbon::now()->format('Y-m-d') <= Carbon::createFromFormat('Y-m-d', $this->start)->addMonthsNoOverflow($i)->format('Y-m-d')
) {
return true;
}
}
return false;
}
$this->start
is the starting date. $this->months
means how many months a payment has to be made in total. So, using the for loop, the current date is being checked against the starting date.
My question basically is, since I want to make this foul proof, is there good way to accomplish this, or will something like a for loop and such work? The above code just feels sloppy to me and it will not produce the correct results I'm afraid.
Upvotes: 3
Views: 1388
Reputation: 39449
Carbon has a few other helper methods for comparison including isToday()
that you can use:
public function isDue()
{
for ($i = 0; $i < $this->months; $i++) {
if ($this->start_date->addMonthsNoOverflow($i)->subDays(5)->isToday()) {
return true;
}
}
return false;
}
This will create a loop for each month as you did before, and check that the adjusted date is today. If it is, the method immediately returns true
.
Upvotes: 4
Reputation: 163978
If I understood correctly, you want to check if the "start date plus few months" is between now and 5 days before now. In this case, you can do this:
if ($this->start->addMonthsNoOverflow($i)->between(now()->subDays(5), now()))
Upvotes: 2