How to Count Weekend Days Between Two Dates in Laravel?

We can use carbon class to get the number of weekend days between two dates in the Laravel framework. To begin with, let’s import the carbon class into the controller.

use Carbon\Carbon;

Once it is imported then we can use it in the controller. Carbon class comes from the carbon package that provides a great function to deal with date and time in PHP. Next, create two dates on which the number of weekend days needs to get.

$fromDate = Carbon::parse('2022-01-01');
$toDate = Carbon::parse('2022-01-31');

Two dates are passed into the parse() method for creating date objects. The first date is assigned to variable $fromDate and the second is assigned to $toDate.

$weekends = $fromDate->diffInDaysFiltered(function(Carbon $date){
      return !$date->isWeekday();
}, $toDate);

dd($weekends);
// Output: 10

In the above, we used the carbon method diffInDaysFiltered() which accepts three parameters in which the first is required and the other two are optional. So we passed a call back function as the first argument and the date object $toDate as the second argument.

In the callback function, we passed the carbon class with the $date variable. The $date variable has a date object that can access the isWeekday() method. The isWeekDay() returns 1 or true when it finds a date between Monday to Friday.

Since we added not (!) with $date->isWeekday() so it always returns 1 or true when it finds a date that day is Saturday or Sunday. In this way the $weekends variable stores all the count. That’s why if we run the above code it returns 10.