In Laravel, Carbon is a popular date/time library that provides an easy way to work with dates in PHP. To get the previous month from a date using Carbon in Laravel, you can use the subMonth() method.
Here’s an example code snippet:
use Carbon\Carbon;
$date = Carbon::parse('2022-03-15');
$previousMonth = $date->subMonth()->format('F Y');
echo $previousMonth; // Output: February 2022
In this example, we’re starting with a date string of ‘2022-03-15’, which is parsed into a Carbon object using the static parse() method. This creates a new Carbon instance representing the given date.
The subMonth() method is then called on the Carbon object, which subtracts one month from the date and returns a new Carbon instance representing the resulting date.
Finally, the format() method is called on the resulting Carbon instance with the ‘F Y’ format characters to output the name of the previous month and the year in the format of “month year”.
The $previousMonth variable is then output using the echo statement, which will output the name of the previous month and the year, in this case “February 2022”.