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

Laravel中如何在Blade模板中对分组集合的组内金额进行求和?

解决Laravel Blade中分组集合求和的问题

我帮你定位到问题啦!你当前代码里求和失败的核心原因是变量名冲突:在第二个foreach循环里,你把循环变量也命名成了$group,这就把外层的分组集合给覆盖了。循环结束后,$group已经变成集合里的单个invoice对象,自然没法调用集合的sum()方法了。

下面给你两种可行的解决方式,按需选择:

方式一:修复Blade视图的变量名,直接在视图中求和

把内层循环的变量名改成$item(避免和外层的分组集合重名),然后直接对原来的分组集合调用sum()即可。同时建议用Laravel Blade的语法代替原生PHP,代码更易读维护:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <title>Department Report</title> 
    <style> 
        body{ font-size:15px; margin: auto; padding: 15px; } 
        table, th, td { border: 1px solid black; } 
    </style> 
</head> 
<body>
@foreach ($group as $category => $items)
    <h2>{{ $category }}</h2>
    <table>
        <tr>
            <td>Name of Item</td>
            <td>Qty</td>
            <td>Amount</td>
        </tr>
        @foreach ($items as $item)
        <tr>
            <td>{{ $item->invoice_product_name }}</td>
            <td>{{ $item->invoice_quantity }}</td>
            <td>{{ $item->invoice_total_price }}</td>
        </tr>
        @endforeach
    </table>
    <p>Total: {{ $items->sum('invoice_total_price') }}</p>
@endforeach
</body> 
</html>

方式二:在控制器提前计算分组总价(更推荐)

把求和逻辑移到控制器,提前计算好每组的总价,再把数据传给视图,这样视图只负责展示,符合MVC的职责分离原则:

修改后的控制器代码

use Carbon\Carbon;

public function departmentSummary($id) { 
    $items = \DB::table('invoices') 
        ->where('user_id', $id) 
        ->where('invoice_status', 1) 
        ->whereDate('created_at', Carbon::today()) 
        ->get(); 

    // 分组并计算每组总价
    $grouped = $items->groupBy('invoice_category')->map(function ($group) {
        return [
            'items' => $group,
            'total' => $group->sum('invoice_total_price')
        ];
    });

    return view('inc.department-summary', [ 'group' => $grouped->all() ]); 
}

修改后的Blade视图代码

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <title>Department Report</title> 
    <style> 
        body{ font-size:15px; margin: auto; padding: 15px; } 
        table, th, td { border: 1px solid black; } 
    </style> 
</head> 
<body>
@foreach ($group as $category => $data)
    <h2>{{ $category }}</h2>
    <table>
        <tr>
            <td>Name of Item</td>
            <td>Qty</td>
            <td>Amount</td>
        </tr>
        @foreach ($data['items'] as $item)
        <tr>
            <td>{{ $item->invoice_product_name }}</td>
            <td>{{ $item->invoice_quantity }}</td>
            <td>{{ $item->invoice_total_price }}</td>
        </tr>
        @endforeach
    </table>
    <p>Total: {{ $data['total'] }}</p>
@endforeach
</body> 
</html>

另外补充一点:如果你的invoice_total_price是数值类型,建议可以用number_format()格式化输出,让总价更美观,比如{{ number_format($data['total'], 2) }}。

内容的提问来源于stack exchange,提问作者Adorablegh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 18:02:37