Skip to content

Instantly share code, notes, and snippets.

@d3vCr0w
Last active January 13, 2024 18:13
Show Gist options
  • Save d3vCr0w/6d318363b3701ed89a28e354eccda392 to your computer and use it in GitHub Desktop.
Save d3vCr0w/6d318363b3701ed89a28e354eccda392 to your computer and use it in GitHub Desktop.
Get last 12 month names from a specific month or date with Laravel - Carbon
<?php
use Carbon\Carbon;
//your class starts here
public function getLastTwelveMonthNames($date){
Carbon::setlocale(config('app.locale'));
$month_names = [
ucfirst((new Carbon($date))->translatedFormat('F'))
];
for($i=1;$i<=11;$i++){
$month_names[$i] = ucfirst((new Carbon($date))->subMonth()->translatedFormat('F'));
$date = (new Carbon($date))->subMonth();
}
return $month_names;
}
//your class ends here
@jekinney
Copy link

jekinney commented Jan 13, 2024

 /**
     * Get a array of month names in the past
     * including current month. Defaults to the last year
     *
     * @param  int $number (of months)
     * @return array
     */
    public static function getLastByCount(int $number = 12): array
    {
        $months = [];
        $current = Carbon::parse(now());

        for ( $count = 0; $count < $number; $count++ ) {
            if ($count == 0 ) {
                $months = [$current->format('F')];
            } else {
                $months[] = $current->subMonth()->format('F');
            }
        }

        return $months;
    }

Returns an array (obviously I did this in Jan, so last 12 is correct at this time):
[ "January", "December", "November", "October", "September", "August", "July", "June", "May", "April", "March", "February" ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment