Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Laravel) check if today is between two dates based on a starting date

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.

like image 751
Hardist Avatar asked Jan 26 '26 15:01

Hardist


1 Answers

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.

like image 109
Martin Bean Avatar answered Jan 29 '26 03:01

Martin Bean