skip to Main Content

I am learning to use groupBy.

In my exercise, I must count the number of tickets that were sold and add the total money collected.

$tickets = Ingresostaquilla::groupBy('tipo')
    ->selectRaw('count(*) as quantity, tipo')
    ->get();

query result

I did the count by type of ticket, but I don’t know how to make it add up to the total amount of money that each ticket collects.

Model table:

table data

I should use SUM, but how do I do it with groupBy?

2

Answers


  1. Considering you get returned a collection, you can use the collection’s sum() method to do that.

    <table>
      <thead>
        <tr>
          <th>Tipo</th>
          <th>Cantidad</th>
        </tr>
      </thead>
      <tbody>
        @foreach ($tickets as $ticked)
          <tr>
            <td>{{ $ticket->tipo }}</td>
            <td>{{ $ticket->cantidad }}</td>      
          </tr>
        @endforeach
      </tbody>
      <tfoot>
        <tr>
          <th>TOTAL</th>
          <th>{{ $tickets->sum('cantidad') }}</th>
        </tr>
      </tfoot>
    </table>
    
    Login or Signup to reply.
  2. $tickets = Ingresostaquilla
            ->selectRaw('tipo, sum(cantidad) as quantity, sum(total)')
            ->groupBy('tipo')
            ->get();  
    

    You can try this query, it will sum the amount of money raised for each type of ticket.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search