I'm trying to get all the Sales records within past 2 years from the database and put them in comparison tables to compare this week/last week, this month/last month, this year/last year sales. Database seems pretty optimized (<400ms for 200k records) but my controller takes an absurd amount of time. Is there a way to optimize the controller or do I have to put a "Please wait, this may take a while" warning to the page?
Clockwork result :

My Model :
<?php
namespace App\Http\Controllers;
use App\Models\Sales;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class StatsController extends Controller
{
public function index()
{
$data = $this->getData();
$this_month = $this->getMonthly($data);
$last_month = $this->getMonthly($data, 1);
$this_year = $this->getYearly($data);
$last_year = $this->getYearly($data, 1);
$this_week = $this->getWeekly($data);
$last_week = $this->getWeekly($data, 1);
return view('employee.stats.index', compact('this_week', 'last_week', 'this_month', 'last_month', 'this_year', 'last_year'));
}
public function getData()
{
$data = Sales::query()
->whereStoreId(Auth::user()->store_id)
->whereYear('created_at', '>=', date('Y') - 1)
->where('status', '>', '1')
->orderBy('created_at')
->get(["price_total", 'created_at']);
return $data;
}
public function getMonthly($data, $minus = 0)
{
$data = $data->groupBy(fn($item) => intval($item->created_at->format('m')));
if(isset($data[date('m') - $minus])){
$get_this = $data[date('m') - $minus]->groupBy(fn($item) => $item->created_at->format('d'));
$this_arr = [];
foreach ($get_this as $day){
$this_arr[intval($day->first()->created_at->format('d'))] = $day->sum('price_total');
}
return json_encode($this_arr);
}else{
return json_encode([]);
}
}
public function getYearly($data, $minus = 0)
{
$data = $data->groupBy(fn($item) => $item->created_at->format('Y'));
if ($data->count()){
$this_arr = [];
foreach ($data as $day){
$this_arr[$day->first()->created_at->format('m')] = $day->sum('price_total');
}
return json_encode($this_arr);
}
else{
return json_encode([]);
}
}
public function getWeekly($data, $minus = 0)
{
$data = $data->groupBy(fn($item) => intval($item->created_at->format('W')));
if(isset($data[date('W') - $minus]))
{
$get_this = $data[date('W') - $minus]->groupBy(fn($item) => $item->created_at->format('D'));
$this_arr = [];
foreach ($get_this as $day){
$this_arr[$day->first()->created_at->format('D')] = $day->sum('price_total');
}
return json_encode($this_arr);
}else{
return json_encode([]);
}
}
}