Home » Php » php – Laravel view foreach with two properties

php – Laravel view foreach with two properties

Posted by: admin February 25, 2020 Leave a comment

Questions:

i need help with my foreach loop in view

Controller.php

$expenses = Expense::groupBy('category_id')->selectRaw('sum(amount) as sum, category_id')->pluck('sum','category_id');

$categories = Category::all();

return view('dashboard.index', compact('expenses','categories'));

index.php

          <table class="table">
            <thead>
              <th>Category</th>
              <th>Expenses</th>
            </thead>
            <tbody>
              @foreach($categories as $category)
              <tr>
                <td>{{ $category->name }}</td>
                @foreach($expenses as $expense)   
              <td>{{ $expense }}</td>
              @endforeach
              </tr>
              @endforeach
            </tbody>
          </table>

I get the output like this.

enter image description here

It outputs the expense 2 times, is there a limiter for “foreach loop” or is there another way on doing this?

How to&Answers:

You need to add a condition for that $category->id is the same as category_id

 @foreach($expenses as $key => $expense)   
    @if($key == $category->id)
    <td>{{ $expense }}</td>
    @endif
@endforeach

The right way to do it is by using join or relationship.

$expenses = Expense::join('categories','categories.category_id','expenses.category_id')->groupBy('expenses.category_id')->selectRaw('sum(expenses.amount) as sum, expenses.category_id','categories.name')->get();

<table class="table">
    <thead>
      <th>Category</th>
      <th>Expenses</th>
    </thead>
    <tbody>

         @foreach($expenses as $expense)   
          <th>{{ $expense->name }}</th>
          <td>{{ $expense->sum }}</td>
         @endforeach
  </tbody>
</table>

Answer:

You should limit the results in controller, but here’s how you can accomplish this in a blade. Not pretty

@foreach ($element['subs'] as $item)
    @if($loop->index < 10)
        // Your code
    @endif
@endforeach

Answer:

You should compare category_id with category->id.

@foreach($categories as $category)
<tr>
    <td>{{ $category->name }}</td>
    @foreach($expenses as $expense)
        @if($expense->category_id == $category->id )   
            <td>{{ $expense->sum }}</td>
        @endif
    @endforeach
</tr>
@endforeach