David David - 1 year ago 77
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();


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 Source

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">
        <th>Charity ID</th>
        <th>Amount ($)</th>
      @foreach($displayPerCharity as $display)
        <td>{{ $display->charity_id }}</td>
        <td>{{ $display->charity_amount }}</td>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download