Sum Of Column Values Using Eloquent In Laravel

  Oct 2023
  ITSolutionsGuides
  Category: Laravel
Sum Of Column Values Using Eloquent In Laravel

Hi Developers,

Lets see how to calculate the Sum Of Column Values Using Eloquent In Laravel. It is widely used in the inventory management Web Applications to calculate the sum of the column values for example ie; calculating the salary, expenses, profit etc. Today we see how to calculate the sum of the column value in the first example and also how to use the both where() and sum() functions together in the second example, it is mainly use to filter the data from the database using the where() condition and the calculate the sum of the column values using the sum() function . Lets see how to calculate Sum Of Column Values Using Eloquent In Laravel.

Optimize your Laravel data handling with our tutorial on calculating column sums using Eloquent. Learn how to efficiently leverage this feature to streamline your application's data processing and gain valuable insights effortlessly.

Let's Start Coding

The below example with calculate sum of the salary column in the entire table ;ie it calculate the sum of salary column from all the records

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
  
class UserController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {       
        $salary= User::sum('salary');
   
        dd($salary);
    }
}

Let's Start Coding

In this example we will see how to use both the where() and the sum() function together,

The below example with calculate sum of the salary column of the male users ;ie it calculate the sum of salary column from all the male users records in the table

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
  
class UserController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {    
        $gender = "male";
        $salary= User::where('gender',$gender)->sum('salary');
   
        dd($salary);
    }
}

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides