Skip to content
Advertisement

Is there a better way to get the 12 months base from the current month and year in laravel using carbon

I have a graph like the attach image below.

How should we fetch 12 months base from the current month year?

Here’s my implementation for the complete 12 month period with month and year filter. Ignore other variables, just look the filter for fetching months.

/** set and iterate over 12 months period from [1 January] up to [12 December] */
    for ($i = 1; $i <= 12; $i++) {

        $months[$i] = $questionAnswer->withCount(['userAnswers' => function ($userAnswer) use ($i, $companyId) {

            $userAnswer->where('skip', 0)
                ->where('company_id', $companyId)
                ->whereMonth('created_at', $i)
                ->whereYear('created_at', Carbon::now()->year);
        }])->get();
    }

But this only get the complete 12 months of the current year. I want to get the 12 months prior to the last month of the current year. For example please see the attach image and observe months prior to the latest month data and in this case is July regardless of the year.

enter image description here

And this is my proposed algorithm and ongoing implementation. If you have much better ways to come up with please post your answer.

// 1. Get data for the current year and previous year
// 2. Get 12 months base from the current month and year and data from previous `year if month is not yet completed for the current year`
// 3. Use filters for the current month year and previous month year (this is what I'm referring from my code)

Advertisement

Answer

use ->subMonth() or subMonths(n)
You can subtract one month or the number of months from Carbon date.
For example

    $n = // no. of months that you can get from a loop;

    $currentDate = now()->subMonths($n);
    $userAnswer->where('skip', 0)
        ->where('company_id', $companyId)
        ->whereMonth('created_at', $currentDate->month)
        ->whereYear('created_at', $currentDate->year);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement