Laravel Blade Sum Foreach

Explanation:

Laravel Blade is a templating engine provided with the Laravel framework. It allows developers to write clean and readable PHP code in their views or templates.

To sum values in a loop using Laravel Blade’s foreach loop, you can follow the below steps:

  1. Create an array or collection of values.
  2. Use the foreach loop directive provided by Blade to iterate over the array or collection.
  3. Inside the loop, add each value to a variable using the += operator to accumulate the sum.
  4. Display the sum after the loop is finished.

Example:

Let’s say we have an array of numbers [10, 20, 30, 40]. We want to calculate the sum of these numbers using a Laravel Blade foreach loop.

    {@verbatim
    // Controller
    public function sumExample()
    {
        $numbers = [10, 20, 30, 40];
        return view('sum-example', compact('numbers'));
    }
    
    // Blade View - sum-example.blade.php
    
@php $sum = 0; @endphp @foreach ($numbers as $number) @php $sum += $number; @endphp @endforeach The sum of numbers is: {{ $sum }}
@endverbatim}

In the above example, we declare a variable “$sum” to store the accumulating sum. Inside the foreach loop, we add each number to the “$sum” variable using the “+=” operator. Finally, we display the sum after the loop using Blade’s curly brace syntax “{{ $sum }}”.

When the sumExample() function is called from the controller, it will render the view “sum-example.blade.php” and display the sum of numbers as “The sum of numbers is: 100”.

This is a basic example demonstrating how to calculate the sum using Laravel Blade’s foreach loop. You can apply the same concept to more complex scenarios based on your requirements.

Leave a comment