Calculate the overall cost from an array of information using Vue.js and Laravel

In a view, I have fields for selecting from and to dates along with branch and spare parts as dropdown options. When I select the date range, it will retrieve data including the branch name, grand total, etc. What I am trying to achieve is getting the total sum of all the grand total prices in the column. For example, if there are 10 data entries each containing a grand total of 1000, I need to calculate the total of these 10 data entries which should be 10,000.

View

<template>
    <div>
        <div class="card">
            <div class="card-header d-flex flex-wrap align-items-center">
                ...
                </button>
                            </td>

                        ...

                    ...                    
                </div>
            <div class="table-responsive">
                <table class="table table-bordered">
                ...
                       
                          

                        </thead>                           
                        </table>
                ...
                        
                </div>
            </div>

        </div>

    </div>
</template>

...

Controller

public function getScrapCollectionReport(Request $request)
    {
        $scrap_total=0;
        $scrap_collections = ScrapCollection::with(['branch:id,name,zone_id','scrap_collection_items','user_verified','user_approved'])->orderBy('id','desc');
        if($request->user()->user_type_id > 2){
            ...
          
          ...

     //  $scrap_total=$scrap_collections->sum('grand_total');

        
        $data['scrap_collections'] = $scrap_collections;
     //  $sum['whole_total']= $scrap_total;

        return $this->sendResponse(true,$data);
    }

Sample Video https://i.stack.imgur.com/svrWa.gif

Answer №1

To determine the total of a specific key in a collection, you can calculate it directly and then merge it with the pagination result.

For example:

$scrap_collections = $scrap_collections->paginate(100);
return collect(['grand_grand_total' => $scrap_collections->sum('grand_total') ] )->merge($scrap_collections);

The grand_grand_total will be included in the paginated object output.

{
    "grand_grand_total": 10000,
    "data": [..],
    "current_page": 1,
    .
    .
    .
}

Alternatively, you can also calculate this using JavaScript's reduce method once you receive the data:

const sumOfGrandTotal = scrap_collections.data.reduce((total, item ) => total + item.grand_total , 0)

Or you can perform the calculation directly in the HTML template:

<tr>
    <th>Grand Total: {{ scrap_collections?.data?.reduce((total, item ) => total + item.grand_total , 0) ?? 0 }} </th>
</tr>

Answer №2

Appreciation for the hard work put in by @mit-kathrotia and @silver

This is what you will see:

 <table class="table table-bordered">
  <thead>
    <tr>
     <th>Grand Total: {{ sumOf_grand_total }} </th>
 </tr>
</thead>

The Method in vue goes like this:

export_default{
props:['branches','user_type_id','zones','scrap_items','price_approval_report','scrap_collection_report','pending_verification_report'],
    data () {
        return {
            scrap_collections   : {},
            current_page: 0,
            from        : 0,
            to          : 0,
            total       : 0,
            sumOf_grand_total:0,
            loading     : false,
            form        : {
                from_date:'',
                to_date:'',
                branch_id:'',
                zone_id:'',
                scrap_item_id:'',
                approval_status:''
            },
            selectedScrapCollection:[]
        }
    },
    created() {
        this.get_data();

        // this.defaults();
    },
methods : {
    get_data(page = 1) {
        this.loading = true;
        var url = '/get-scrap-collection-report'
        axios.get(url+'?page='+page+'&from_date='+this.form.from_date+'&to_date='+this.form.to_date+'&branch_id='+this.form.branch_id+'&approval_status='+this.form.approval_status
        +'&zone_id='+this.form.zone_id+'&scrap_item_id='+this.form.scrap_item_id+'&scrap_collection_report='+this.scrap_collection_report+'&price_approval_report='+this.price_approval_report+'&pending_verification_report='+this.pending_verification_report)
        .then(response => {
            this.loading      = false;
            this.scrap_collections    = 
            response.data.data.scrap_collections;
            this.sumOf_grand_total=response.data.data.sumOf_grand_total;
            this.current_page = this.scrap_collections.current_page;
            this.from         = this.scrap_collections.from;
            this.to           = this.scrap_collections.to;
            this.total        = this.scrap_collections.total;
            this.loading      = false;
        })
        .catch(e => {
            this.loading = false;
            toastr.error("Couldn't load data");
        })
    },

}
}

In Controller

An additional line has been included after:

 $data['scrap_collections'] = $scrap_collections;
    $data['sumOf_grand_total']= $scrap_total;

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

JavaScript function to provide a range of numbers based on a specified number and step value

I am looking for a solution to dynamically generate content based on the number of slides/steps using JavaScript. Any suggestions on how to best achieve this? Thanks in advance! switch(this.currentSlide) { case 1: return '1-12'; ...

The content of the string is not appearing

I've hit a snag while trying to create components and templates. I'm closely following the instructions provided in this link: My code is very similar to the one shown in the instructional video (except for the error, of course). The issue I&ap ...

How can you access the most recent user information in Vuex following a user profile update?

Struggling with making a user's data "reactive" in Vuex after updating their profile? Here's the situation: In my App.vue, I check a user's details using the created() hook as follows: async created() { await this.$store.dispatch( ...

Having difficulty distinguishing between public and private packages

Recently, I have been utilizing the Yarn package manager within my Laravel project to install public JavaScript libraries like jQuery and Bootstrap. To ensure all packages are readily available, I included a single line in my .yarnrc configuration file spe ...

Display the content of a Vue file directly on the webpage

I am currently developing a website to showcase UI components using plain CSS. The project is built with Vue, utilizing standard HTML and CSS. One of the key features I am working on is providing users with two views for each component: 'Preview' ...

Creating a Vue JS project that utilizes both HTTP and HTTPS URLs for improved security

I'm currently utilizing Vue JS with the webpack template and dev mode. I have a question regarding how to configure my server to allow for both HTTPS and HTTP protocols simultaneously. I understand that enabling HTTPS can be done by simply adding "ht ...

Having trouble with Vue Router at the root path ("/") while utilizing Quasar Server-Side Rendering (SSR)?

THE ISSUE AT HAND I have a Quasar CLI (Webpack) setup for my app, and everything runs smoothly in SPA mode. However, when I switch to SSR, an unexpected issue arises. The Vue Router redirect from path "/"" to "/index" does not function as expected. Instea ...

Obtaining the current value with each keystroke

While working with vue.js, I'm building a table that contains an input field called quantity. However, when I start typing the first word, it shows 'empty' on the console. If I type 3, it displays empty; and if I type 44, it prints 4. I am ...

Guide to invoking a mixin function within middleware

Is there a way to invoke the mixin function within middleware using NUXT.js? This is what I have attempted: export default function(context) { // initialize auth token from local storage or cookies context.initAuth(context.req) if (!context.store. ...

Is there a way to specify a custom model type in lighthouse-php under a different name?

When working with the Lighthouse package for GraphQL in Laravel, I have a model named "ClassA" that needs a type declaration as "TypeA". What is the recommended best practice to achieve this? ...

Choose Option 1 in order to proceed with selecting Option 2 and displaying the outcome in the VueJs framework

Looking for help on how to show the text value from multiple related select fields. I want Option 1 to display a list of parent options. Upon selecting an Option 1, it should determine what values are available in Option 2 select field. After selection, ...

Why doesn't updating Vuex state cause a re-render of the component?

I implemented a navigation bar that changes its display based on authentication: <template> <div id="routing"> <b-navbar variant="light" type="light"> <b-navbar-brand> <img id="drage" src="../assets/icon.svg" ...

Dynamically load components based on the URL parameters in NuxtJS

In my Nuxt page, I have split it into two sections. The first section is a regular template structure that displays dynamic content based on the URL parameter. The second section consists of a component that needs to load based on this data. I've atte ...

Copy both the image and JSON object to the clipboard

I am attempting to utilize the clipboard API to write an image and JSON object to the window clipboard. I am working with Vue and Electron and have successfully written an image and plain text, but I encounter an error when trying to write a JSON object: ...

What is the solution for resolving the error "Uncaught TypeError: Cannot read property '_wrapper' of undefined" while utilizing webpack in conjunction with Vue?

When I am utilizing axios to fetch data from the database, I receive a server response in an array format: In my HTML tags: The JavaScript code appears as follows: data() { return { departments: { id: 0, ...

The `vue-select` npm package is experiencing issues with the onChange event functionality and is not working

I am currently utilizing [email protected]. By the way, I am wondering how to trigger the @change event when selecting another option? This is the existing codebase: <v-select v-model="selected" :options="['Vue.js','React&apos ...

What steps can be taken to ensure that the v-model input is not updated?

Typically, when a user enters a value in an input field, it automatically updates a model. However, I am looking to temporarily prevent this automatic update. In my application, I have a canvas where users can draw grids by entering lengths and widths in i ...

Having trouble installing npm on my Laradock environment

After setting up a Laravel project with Laradock, running npm install resulted in the following error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f31303b3a722c3e2c2c1f6b7166716f">[email protected]</a> i ...

The Vue3 counterpart of vNode.computedInstance

I'm currently in the process of upgrading my app from Vue2 to Vue3, but I've hit a roadblock when it comes to dealing with forms. For my form elements, such as FormInput, FormTextArea, and FormCheckbox, I have been using Single File Components ( ...

Error: The "issuerBaseURL" parameter needs to be a properly formatted URI

The Vue app is experiencing difficulty loading and keeps showing an error related to the issuerBaseURL, stating that it must be a valid URI. No matter what changes I make, the issue persists. I have been following this tutorial: TypeError: "issuerBaseUR ...