D
D
Darkhan Kamaliev2019-09-25 11:33:54
Laravel
Darkhan Kamaliev, 2019-09-25 11:33:54

How to correctly form an eloquent request for chartjs by month?

Good day, tell me about the generation of reports for a line chart (by months) in chartjs.
At the moment there is such a design, but its effectiveness is questionable.

spoiler
class ChartController extends Controller
{
    public $monthsList = array(
        "1" => "Январь", "2" => "Февраль", "3" => "Март",
        "4" => "Апрель", "5" => "Май", "6" => "Июнь",
        "7" => "Июль", "8" => "Август", "9" => "Сентябрь",
        "10" => "Октябрь", "11" => "Ноябрь", "12" => "Декабрь");

    public function index()
    {
        $month_hotels_select = Hotel::query()->select(DB::raw('count(*) as count,MONTH(created_at) as month'))->orderBy('created_at')->groupBy(DB::raw('MONTH(created_at)'))->get();
        $count_hotels = collect([]);
        $month_hotels = collect([]);

        foreach ($month_hotels_select as $item) {
            $count_hotels->push($item->count);
            $month_hotels->push($this->monthsList[$item->month]);
        }
        return response()->json(
            [
                'labels' => $month_hotels,
                'datasets' => array(
                    [
                        'label' => 'Количество сетей',
                        'backgroundColor' => array([
                            '#ff0000',
                        ]),
                        'data' => $count_hotels
                    ],
                )],
            200);
    }
}

I don’t understand how to correctly form an array so that there are 12 months and each result becomes in the right order in the data array.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question