Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
public function lineChart () {
if (request()->ajax()) {
$from = session()->has('from') ? session('from') : (new Carbon('first day of January ' . date('Y')))->toDateTimeString();
$to = session()->has('to') ? session('to') : now()->toDateTimeString();
$period = CarbonPeriod::create($from, $to);
$range = [];
$dbData = [];
$months = [];
foreach($period as $date){
$range[$date->format('Y-m')] = 0;
$months[$date->format('Y-m')] = $date->formatLocalized('%Y %B');
}
$lineCharts = LineChart::select(DB::raw('SUM(amount) as totalAmount'), DB::raw('DATE_FORMAT(`created_at`,\'%Y-%m\') as monthYear'));
if (session('from')) {
$lineCharts->where('created_at', '>=', (new Carbon(session('from')))->toDateTimeString());
}
if (session('to')) {
$lineCharts->where('created_at', '<=', (new Carbon(session('to')))->toDateTimeString());
}
$lineCharts = $lineCharts->groupby('monthYear')->get();
if ($lineCharts) {
foreach($lineCharts as $lineChart){
$dbData["{$lineChart->monthYear}"] = $lineChart->totalAmount;
}
}
$data = array_replace($range, $dbData);
return response()->json(['data' => array_values($data), 'months' => array_values($months)]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment