Skip to content

Instantly share code, notes, and snippets.

@uno-de-piera
Last active June 5, 2019 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uno-de-piera/a0f7cf573f81cff2e81ebb60c6810b59 to your computer and use it in GitHub Desktop.
Save uno-de-piera/a0f7cf573f81cff2e81ebb60c6810b59 to your computer and use it in GitHub Desktop.
<?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