Vue JS: Easily Calculate the Total Sum of All Columns

An example of a query in the backend controller

 public function show($id)
    {
       $structural = DB::table('attendance')->where('payroll_daily_id',$id)
       ->where('assignment','STRUCTURAL')
       ->select('payroll_daily_attendance.*')
       ->get();

       $fetch = [];
       foreach($structural as $key){
            if(!isset($fetch[$key->wrk_id]['total_ot']) && !isset($fetch[$key->wrk_id]['total_days']) ){
               $fetch[$key->wrk_id]['total_ot'] = 0;
               $fetch[$key->wrk_id]['total_days'] = 0;
             }
             $fetch[$key->wrk_id]['wrk_id'] = $key->wrk_id;
             $fetch[$key->wrk_id]['daily_rate'] = $key->rate;
             $fetch[$key->wrk_id]['date'][$key->date]['work_hours'] = $key->reg_hour;
             $fetch[$key->wrk_id]['date'][$key->date]['adj_hour'] = $key->adj_hour;
             $fetch[$key->wrk_id]['total_ot'] += $key->ot_adj;
             $fetch[$key->wrk_id]['total_days'] += $key->reg_hour;
             
         }
         return $fetch;
     
    }

The displayed results from the executed query

1: {total_ot: 1, total_days: 24, wrk_id: 1, daily_rate: 575,...}
daily_rate: 575
date: {2020-09-24: {work_hours: 8, adj_hour: 0}, 2020-09-25: {work_hours: 8, adj_hour: 0},...}
total_days: 24
total_ot: 1
wrk_id: 1
2: {total_ot: 0, total_days: 48, wrk_id: 2, daily_rate: 450,...}
daily_rate: 450
date: {2020-09-24: {work_hours: 8, adj_hour: 0}, 2020-09-25: {work_hours: 8, adj_hour: 0},...}
total_days: 48
total_ot: 0
wrk_id: 2
3: {total_ot: 0, total_days: 8, wrk_id: 3, daily_rate: 560,...}
daily_rate: 560
date: {2020-09-24: {work_hours: 8, adj_hour: 0}}
total_days: 8
total_ot: 0
wrk_id: 3

Calculation process implemented in my Vue application

  <table class="table table-sm borderless">           
          <thead>
          <th></th>
          <th></th>
          </thead>
          <tbody>
          <tr  v-for="fetch in assignmentTotal">
          <td style="height:10px;">Structural</td>
          <td style="height:10px;">{{(fetch.total_days / 8) * fetch.daily_rate}}</td>
          </tr>

          </tbody>
          </table>

Answer №1

In PHP, you can calculate the sum while in Vue.js your focus should be on displaying the result.

$sum = [];
$total_amount = 0;

foreach ($items as $element) {
    // ...
    $total_amount += ($element->quantity * $element->price);
}

$sum['total_amount'] = $total_amount;

return $sum;

Answer №2

My recommendation is to utilize Vue.js computed property

Instead of manually calculating the total with ({{(fetch.total_days / 8) * fetch.daily_rate)}), consider calling returnTotal()

computed:{
returnTotal:function(){
var sum = this.assignmentTotal.reduce((acc,item)=> acc+ (item.total_days / 8) * item.daily_rate), 0);
  return sum;
}
}

Appreciate your attention

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing the Context Object in a Slack API Bolt Project for seamless property transfer between methods

I'm currently working on a Slack app using the JavaScript Bolt framework. This app essentially listens for specific message keywords in channels and then forwards those messages to the users of the app. My main goal is to add a permalink to the forwa ...

Using three.js to input text instead of particles within a particle cloud

I have a unique three.js codepen project where square particles drift through the space. However, I am now looking to enhance it by incorporating text (perhaps using geometry?) instead of the square particles, creating a word/tag cloud effect. Is this eve ...

Alter the row's color using the selection feature in the module

Is there a way to change the color of a row when a specific property has a certain value? I found a solution for this issue on Stack Overflow, which can be viewed here: How to color row on specific value in angular-ui-grid? Instead of changing the backgro ...

Error: Trying to break down a non-iterable object is not valid

Currently working on an Ionic React app and encountering the following error: Error: TypeError - Invalid attempt to destructure non-iterable instance Once I run the program, the error occurs at this point: . Shown below is a snippet of my code: import ...

A guide on injecting a Class with a constructor into a Resource Class in Laravel

Encountering an issue in Laravel Resource "App\Http\Resources\OrderResource::__construct(): Argument #2 ($orderLogRepository) must be of type App\Interfaces\OrderLogRepositoryInterface, int given, called in /var/www/vendor/lar ...

Is there a way to retrieve the name of a JSON or obtain the file path using NodeJS Express Router?

I've been experimenting with adding a named routers feature to the Express router for my NodeJS project. I managed to implement it successfully, but there's one thing I'm stuck on... the path. Specifically, when I have a route setup like thi ...

Can we safely save a value in session storage directly from the main.js file in Vue?

Throughout the user session managed by Vuex, I have a session storage value set to false that needs to be monitored. Setting up this value directly from the main.js file looks like this: import { createApp } from 'vue'; import App from './Ap ...

What is the process for assigning a PHP function's return value to a JavaScript variable?

Is there a way to retrieve a value from a PHP function and assign it to a JavaScript variable? As shown in the following example: PHP: // Destination folder for downloaded files $date = date('m.d.y'); mkdir("uploads/" . $date, 0777, true); $ ...

Renew the Look of Dynamic HTML with Updated Styles

In the middle of my website, there is a console that contains links to dynamically update its content using javascript. Everything works smoothly, but the new HTML added dynamically does not have any styling applied to it. Is there a way to refresh the CS ...

Javascript code to verify whether the page is currently positioned at the top

How can I use JavaScript to determine if the page is at scroll(0,0)? I have a full-page slider that needs to pause when the page is no longer at the top. The page may not be scrolled manually, as there are internal HTML # links that could load the page d ...

The render function is not being executed due to a disruption in the code flow

Within the given code snippet, there is a peculiar issue with the render function being called inside the loop below. Strangely, the console.log statement before the function call executes successfully, but the one directly inside the function does not s ...

Firestore generates an error stating that 'onSnapshot() must have 1 to 4 arguments'

I am having trouble retrieving all unread messages for the current user from Firebase. The issue arises when using onSnapshot() as it initially fetches the required data but fails to do so when a new document is added, resulting in an error. FirebaseErro ...

How come TinyMCE is showing HTML code instead of formatted text?

I have been working on integrating TinyMCE with React on the frontend and django(DRF) on the backend. After saving data from TinyMCE, it retains the HTML tags when displayed back, like this: <p>test</p> <div>Test inside div</div> ...

Utilize JavaScript to randomly choose images as background tiles in HTML

Currently, I am in the process of developing a game using HTML/CSS/JavaScript. My background is currently set to a single image (100px / 100px) being repeated vertically and horizontally to tile across the entire page body; CSS: body { background-ima ...

In what way can an item be "chosen" to initiate a certain action?

For example, imagine having two containers positioned on the left and right side. The left container contains content that, when selected, displays items on the right side. One solution could involve hiding elements using JavaScript with display: none/in ...

Interactive Thumbnail Previews

There seems to be an issue with the thumbnail links on my page. The leftmost and rightmost links work fine, but the middle ones are not functioning properly when clicked. The PHP code used to generate these links is the same for all of them, so it's p ...

Is there a way to transform a six-digit input into a date format using vue/JavaScript?

I've explored various solutions for this issue, but they all seem to be backend-focused. What I need is a Vue/JavaScript method. I have a string containing IDs, with the first 6 digits representing the date of birth and the final 4 digits being a pers ...

Updating the src of an iframe and adding an onclick event to a link using JavaScript

Looking to design a page that accommodates both login and sign up functionalities by dynamically updating the src of an iframe. In the navigation bar, there is: <li id="change"><a onclick="sign()">Sign up</a></li> And within the ...

Receive the complete HTML page as a response using JavaScript

When making an Ajax post to a specific page, I either expect to receive an ID as a response if everything goes smoothly, or I might get a random html page with a HTTP 400 error code in case of issues. In the event of an error, my goal is to open the enti ...

Having trouble deactivating date selections in Vue.js Material Datepicker

Can someone assist with the following HTML code: <datepicker :date="child" :option="option" v-model="child.dob" @change="updatechildDOB(child)" :disabled="disabled"></datepicker> Here are the available options: option: { type: 'd ...