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

Laravel如何将过去一年的月度销售额数据传递至视图并展示?

修复逻辑并传递数据到视图展示月度销售额

首先你的原代码存在逻辑问题:每次查询仅限定created_at >= 往前推N个月的时间,这会导致后续月份的销售额包含前面所有月份的订单数据(比如查询1个月前的销售额时,会把最近1个月到现在的所有订单都算进去),所以得先修正查询逻辑,精准统计每个月的销售额。

1. 后端修正并收集数据

在控制器中,我们可以循环生成过去12个月的起止时间,查询对应月份的销售额并存入数组,再传递到视图:

// 初始化数组存储月度销售数据
$salesData = [];
$currentDate = now();

// 循环遍历过去12个月(从11个月前到当前月)
for ($i = 11; $i >= 0; $i--) {
    // 获取当前循环对应的月份的起始和结束时间
    $monthStart = $currentDate->copy()->subMonths($i)->startOfMonth();
    $monthEnd = $currentDate->copy()->subMonths($i)->endOfMonth();
    
    // 查询该月份内的订单总金额
    $monthlySales = Order::whereBetween('created_at', [$monthStart, $monthEnd])
        ->sum('order_price');
    
    // 将月份名称和销售额存入数组,可根据需求调整月份格式(比如'2024年5月')
    $salesData[] = [
        'month' => $monthStart->format('Y-m'),
        'sales' => $monthlySales
    ];
}

// 将数据传递到视图,假设视图路径为 sales/monthly.blade.php
return view('sales.monthly', compact('salesData'));

2. 视图中展示数据

方式一:用表格展示

在对应的Blade视图文件中,通过循环遍历$salesData渲染表格:

<div class="sales-table">
    <h3>过去12个月销售额</h3>
    <table border="1">
        <thead>
            <tr>
                <th>月份</th>
                <th>总销售额</th>
            </tr>
        </thead>
        <tbody>
            @foreach($salesData as $item)
            <tr>
                <td>{{ $item['month'] }}</td>
                <td>{{ number_format($item['sales'], 2) }}</td> <!-- 格式化金额为两位小数 -->
            </tr>
            @endforeach
        </tbody>
    </table>
</div>

方式二:用图表可视化展示(以Chart.js为例)

如果需要更直观的图表展示,可以引入Chart.js生成柱状图或折线图:

<div class="sales-chart">
    <h3>过去12个月销售额趋势</h3>
    <canvas id="monthlySalesChart" width="600" height="300"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    // 将PHP数组转为JS可用的数据
    const monthLabels = {!! json_encode(array_column($salesData, 'month')) !!};
    const salesValues = {!! json_encode(array_column($salesData, 'sales')) !!};

    // 初始化图表
    const ctx = document.getElementById('monthlySalesChart').getContext('2d');
    new Chart(ctx, {
        type: 'bar', // 可选'line'改为折线图
        data: {
            labels: monthLabels,
            datasets: [{
                label: '月度销售额',
                data: salesValues,
                backgroundColor: 'rgba(75, 192, 192, 0.6)',
                borderColor: 'rgba(75, 192, 192, 1)',
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: '销售额'
                    }
                },
                x: {
                    title: {
                        display: true,
                        text: '月份'
                    }
                }
            }
        }
    });
</script>

内容的提问来源于stack exchange,提问作者Muhammet aytaç

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:40:37