简体   繁体   中英

Laravel - Math computations in blades

Is it possible to add two integers from the database inside a blade?

To give a scenario, I have a controller that compacts a collection of orders table.

$solditems =  DB::table('orders')
            ->where('status', 'served')
            ->orderBy('id')
            ->get();

        return view('salesreports.sellingitems.index', compact('solditems'));

And I used those like this in my blade.

                <table class="table table-hover">
                    <tr>
                        <th>ID</th>
                        <th>Item</th>
                        <th>Sales</th>
                    </tr>
                <thead>
                </thead>
                    <tbody>
                        @forelse($solditems as $solditem) 
                            <tr>
                                <td>{{$solditem->id}}</td>
                                <td>{{$solditem->item}}</td>
                                <td>{{$solditem->subtotal}}</td>
                            </tr>
                        @empty
                        @endforelse
                    </tbody>
                </table>

Now, what I want to do is to combine an item that has same item names or $solditem->item while adding up there subtotals.

For example;

ID #1 Apple = 50
ID #2 Apple = 80

Will become this;

ID #1 Apple = 130

I tried using groupBy on query builder so an item with same name will only show once, but I'm having problems designing an algorithm adding up the subtotal.

Try this one, This gives you sum of cost with same item name for all items.

$solditems =  DB::table('orders')
              ->where('status', 'served')
              ->select('orders.*',DB::raw('SUM() as total'))
              ->groupBy('orders.item')
              ->orderBy('id')
              ->get();

You could take advantage of Laravel's collection methods. You can use the GroupBy method to create grouped subarrays by product name and foreach of those group using the Sum method return the sum of the total column.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM