我有一个管理仪表板,显示折线图,其中包含每月注册的用户数量。我正在从数据库获取数据,似乎一切正常,但功能相当大,我想知道是否有更优化和更有效的方法来获取和返回相同的数据?
我将此函数分配给一个变量并将其传递到我的视图。
// Get Monthly Registered Users This year
public function monthlyRegisteredUsers()
{
$janUsers = User::whereMonth('created_at', 1)->whereYear('created_at', Carbon::now()->format('Y'))->count();
$febUsers = User::whereMonth('created_at', 2)->whereYear('created_at', Carbon::now()->format('Y'))->count();
$marUsers = User::whereMonth('created_at', 3)->whereYear('created_at', Carbon::now()->format('Y'))->count();
$aprUsers = User::whereMonth('created_at', 4)->whereYear('created_at', Carbon::now()->format('Y'))->count();
$mayUsers = User::whereMonth('created_at', 5)->whereYear('created_at', Carbon::now()->format('Y'))->count();
$junUsers = User::whereMonth('created_at', 6)->whereYear('created_at', Carbon::now()->format('Y'))->count();
$julUsers = User::whereMonth('created_at', 7)->whereYear('created_at', Carbon::now()->format('Y'))->count();
$augUsers = User::whereMonth('created_at', 8)->whereYear('created_at', Carbon::now()->format('Y'))->count();
$sepUsers = User::whereMonth('created_at', 9)->whereYear('created_at', Carbon::now()->format('Y'))->count();
$octUsers = User::whereMonth('created_at', 10)->whereYear('created_at', Carbon::now()->format('Y'))->count();
$novUsers = User::whereMonth('created_at', 11)->whereYear('created_at', Carbon::now()->format('Y'))->count();
$decUsers = User::whereMonth('created_at', 12)->whereYear('created_at', Carbon::now()->format('Y'))->count();
$data = [$janUsers, $febUsers, $marUsers, $aprUsers, $mayUsers, $junUsers, $julUsers, $augUsers, $sepUsers, $octUsers, $novUsers, $decUsers ];
return $data;
}
它所做的就是获取每个月的注册用户数并将其分配给一个变量,然后返回包含每月用户数的数组。这可以改进吗?
人到中年有点甜