David David - 4 months ago 6
PHP Question

Display total amount for a charity in Laravel 5.2

I have a charity_donations table which holds a charity_id, amount donated for that charity, among other fields. This is how it looks.

Charity Donations Table

What I need to do is I need to groupBy each charity ID, then count how much money was donated for that particular charity. And most importantly, I need to display that in a view.

Some thing like this:

Charity ID | Total

1 | $1,200
....

I have tried this,

$displayPerCharity = CharityDonation::select(DB::Raw('charity_id, COUNT(*) as count'))->groupBy('charity_id')->get();

dd($displayPerCharity);


That counts the charity IDs, then gives me the total for each charity. But I need total amount for each charity, then display in view.

Answer

Well how you display it is entirely up to how you want it to look.

If you're just stuck on how to get each charity ID and amount out, then you can just do this with a foreach loop.

Here's an example using a Bootstrap responsive table. This assumes that after you have run your query you have passed it on to the view as a variable called $displayPerCharity.

<div class="table-responsive">
  <table class="table">
    <thead>
      <tr>
        <th>Charity ID</th>
        <th>Amount ($)</th>
      </tr>
    </thead>
    <tbody>
      @foreach($displayPerCharity as $display)
      <tr>
        <td>{{ $display->charity_id }}</td>
        <td>{{ $display->charity_amount }}</td>
      </tr>
      @endforeach
    </tbody>
  </table>
 </div>
Comments