7

I want to sum tot_Price and unit_Price respectively so that I can analyze the average of these two attributes.

<tr>
    <td>{{ $X_land->house_Type }}</td>
    <td class="address">{{ $X_land->the_Location }}</td>
    <td>{{ $X_land->tot_Price }}</td>
    <td>{{ $X_land->tran_Area }}</td>
    <td>{{ $X_land->unit_Price }}</td>
    <td><button id="opener<?php echo $opencount?>">詳細資訊</button></td>
</tr>

How should I do this?
Thanks.

1
  • just use a temporary total container, just += those values Commented Aug 23, 2016 at 1:10

3 Answers 3

11

You could add sum variable for both tot_Price and unit_Price and add in foreach loop

<?php $sum_tot_Price = 0 ?>
<?php $sum_unit_Price = 0 ?>
@foreach ($yourData as X_land)
<tr>
    <td>{{ $X_land->house_Type }}</td>
    <td class="address">{{ $X_land->the_Location }}</td>
    <td>{{ $X_land->tot_Price }}</td>
    <td>{{ $X_land->tran_Area }}</td>
    <td>{{ $X_land->unit_Price }}</td>
    <td><button id="opener<?php echo $opencount?>">詳細資訊</button></td>
</tr>
<?php $sum_tot_Price += $X_land->tot_Price ?>
<?php $sum_unit_Price += $X_land->unit_Price ?>
@endforeach

<tr>
    <td>Sum tot_Price {{ $sum_tot_Price}}</td>
    <td>Sum unit_Price {{ $sum_unit_Price}}</td>
</tr>
Sign up to request clarification or add additional context in comments.

1 Comment

Works!! Thank for your tutorial.
6

Assume:

@foreach($lands as $X_land)
<tr>
    <td>{{ $X_land->house_Type }}</td>
    <td class="address">{{ $X_land->the_Location }}</td>
    <td>{{ $X_land->tot_Price }}</td>
    <td>{{ $X_land->tran_Area }}</td>
    <td>{{ $X_land->unit_Price }}</td>
    <td><button id="opener<?php echo $opencount?>">詳細資訊</button></td>
</tr>
@endforeach

You can get total like this:

{{$lands->sum('tot_Price')}}
{{$lands->sum('unit_Price')}}

Or you can get average:

{{$lands->avg('tot_Price')}}
{{$lands->avg('unit_Price')}}

1 Comment

Hi, I had add pagination method into my project. I run into a problem that {{$lands->sum('tot_Price')}} will only sum the current page's tot_Price, how should I do to calculate tot_Price of all pages but not just one page? Is there any solution to create some code in controller? Thanks for helping me with this.
1

To be very simple,

You need to focus on the @foreach loop first,
e.g @foreach($people as $person)

and there is the salary which you can access in foreach, Through $person->salary

If you want to calculate the sum of salaries then use a simple sum like this,

$people->sum('salary'), Remember not use $person

In your case
{{$lands->sum('tot_Price')}}
{{$lands->sum('unit_Price')}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.