I have display quantity and price attributes on my table from database but for some reasons I don't save the total into database but I display total by multiplying quantity * total
on the table when data is being fetched.
Total for every column on my table is being displayed accurately. Is there a way that I can add all total columns on the table in my html?
PS: with my code, it only displays the total of the current column of the table
Table
<tbody>
@foreach($items as $items)
<tr>
<td>{{$item>id }}</td>
<td>{{$item->quantity}}</td>
<td>{{ $item->price}}</td>
<td>{{ $item->quantity * $item->price}}</td>
</tr>
@endforeach
<p>Sum: {{ $item->quantity * $item->price}}</p>
</tbody>
<tbody>
{{ $total = 0 }}
@foreach($items as $items)
<tr>
<td>{{$item>id }}</td>
<td>{{$item->quantity}}</td>
<td>{{ $item->price}}</td>
<td>{{ $item->quantity * $item->price}}</td>
{{ $total = $total + ($item->quantity * $item->price) }}
</tr>
@endforeach
<p>Sum: {{ $total }}</p>
</tbody>
You can use blade's @php
directive like this
<tbody>
@php
$total = 0
@foreach($items as $items)
<tr>
<td>{{$item>id }}</td>
<td>{{$item->quantity}}</td>
<td>{{$item->price}}</td>
<td>{{$total = $total + ($item->quantity * $item->price)}}</td>
</tr>
@endforeach
<p>Sum: {{ $total }}</p>
@endphp
</tbody>
Try the following:
{{ $sum = 0 }}
<tbody>
@foreach($items as $items)
<tr>
<td>{{$item>id }}</td>
<td>{{$item->quantity}}</td>
<td>{{ $item->price}}</td>
<td>{{ $item->quantity * $item->price}}</td>
</tr>
$sum+ = $item->quantity * $item->price;
@endforeach
<p>Sum: {{ $sum }}</p>
</tbody>
I assume here $items
is a Illuminate\\Support\\Collection
. You can calculate a sum using a closure:
$items->sum( function ($item) {
return $item->quantity * $item->price;
});
Or in your blade template:
{{ $items->sum( function ($item) {
return $item->quantity * $item->price;
}); }}
See Laravel Collections docs .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.