W3docs

Calculate difference between two dates using Carbon and Blade

To calculate the difference between two dates using Carbon and Blade, you can use the following steps:

To calculate the difference between two dates using Carbon and Blade, you can use the following steps:

  1. Install Carbon using Composer by running the following command:

Example of installing Carbon using Composer in PHP

composer require nesbot/carbon
  1. In your Blade template, use Carbon to parse the dates and calculate the difference between them:

Example of using Carbon to parse the dates and calculate the difference between them in PHP Blade template

<?php
// Parse the dates using Carbon
$startDate = \Carbon\Carbon::parse($date1);
$endDate = \Carbon\Carbon::parse($date2);

// Calculate the difference between the dates
$difference = $startDate->diffInDays($endDate);
  1. You can then output the difference in your Blade template using Blade syntax:
The difference between the two dates is {{ $difference }} days.

Note that in this example, $date1 and $date2 are variables that contain the dates you want to compare. Ensure they are valid date strings (e.g., Y-m-d or Y-m-d H:i:s) so Carbon::parse() works reliably. You can pass these variables to your Blade template from your controller or other code. For example, in your controller, you can return the view with return view('your-view', compact('date1', 'date2'));.

While this approach works directly in Blade, it is generally considered a best practice to move date calculations to the controller or a service class to keep templates focused on presentation. For human-readable output instead of raw numbers, you can use $startDate->diffForHumans($endDate).