Ad

Laravel, Using Date Differences With Multiple Variables

- 1 answer

I know that I can use $date_diff($request->start_date, $request->end_date) to get the difference between two dates, but I need an explicit date comparison to say "If End date is 60 days greater than start date, print 'error'"

So $request->end_date > $request->start_date works in general, but I can't figure out the best way to check if it's 60 days or more than the start date.

What's the best way to do this?

$request->start_date->format('Y-m-d');
$request->end_date->format('Y-m-d');

if($request->end_date > $request->start_date) { 
 echo 'Error';
}
Ad

Answer

You can accomplish this in many ways.

One solution is to make use of the diffInDays() method of Carbon.

if ($startDate->diffInDays($endDate) > 60)
{
  // throw an error..
}

Or you could add days to the start date, to then compare if this is before or after the second date:

if ($startDate->addDays(60)->isBefore($endDate))
{
  // throw an error..
}

For more info, check this section of the Carbon docs.

Ad
source: stackoverflow.com
Ad