You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Nova Trends:如何在保留每日图表的同时展示统计周期内累计注册用户总数

Absolutely, you can make this work while keeping the daily chart structure you already have! The key is to transform the daily count data into cumulative totals before passing it to the Trends display. Here are two practical approaches you can use:

Option 1: Quick Map Transformation (Simple Implementation)

This approach uses the map() method to replace each day's count with the cumulative total up to that date:

return $this->countByDays($request, User::class)
    ->map(function ($dailyCount, $date) {
        // Calculate total users registered on or before this date
        return User::whereDate('created_at', '<=', $date)->count();
    })
    ->showLatestValue();

How it works:

  • The original countByDays() fetches the daily registration count for your selected period
  • The map() function runs for each date in the range, swapping the single-day number with the total users registered from the start up to that date
  • showLatestValue() will now display the final cumulative number (like your example of 50) instead of the individual day's count

Option 2: Optimized Cumulative Calculation (Better for Large Datasets)

If you're working with a large user base or long date range, the first option will run a database query for every day in your period. This optimized version cuts that down to a single query:

// Fetch all daily counts in one database call
$dailyData = $this->countByDays($request, User::class)->query()->get();

// Calculate cumulative totals in memory
$cumulativeTotal = 0;
$cumulativeData = $dailyData->map(function ($item) use (&$cumulativeTotal) {
    $cumulativeTotal += $item->aggregate;
    return [
        'date' => $item->date,
        'aggregate' => $cumulativeTotal,
    ];
});

// Build the chart with the transformed cumulative data
return $this->chart($request)
    ->dataset('Cumulative User Registrations', $cumulativeData->pluck('aggregate')->all())
    ->dates($cumulativeData->pluck('date')->all())
    ->showLatestValue();

Why this is better:

  • Only one database call to fetch all daily counts, reducing load on your server
  • All cumulative calculations happen in memory, which is significantly faster
  • The chart retains its daily structure, but each data point now represents the total number of users registered up to that specific day

Either approach will keep your daily chart layout intact while updating the displayed value to show the cumulative total across your entire selected period.

内容的提问来源于stack exchange,提问作者Diogo Mendonça

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 12:48:12