Laravel withSum() with Where Condition: Aggregating Related Models with Filtering

Published on : June 11,2023
Laravel withSum() with Where Condition: Aggregating Related Models with Filtering

In Laravel, the withSum() method provides a convenient way to aggregate related models' data. It allows you to calculate the sum of a specific column across related models. Additionally, you can apply a where condition to filter the results before performing the aggregation. In this tutorial, we will explore how to use the withSum() method in Laravel with a where condition. By the end of this guide, you'll be able to perform filtered aggregations on related models in your Laravel applications.


Step 1: Define Eloquent Relationships

First, ensure that you have established the appropriate Eloquent relationships between your models. For example, let's consider a scenario where you have a "User" model that has many "Orders" associated with it. Define the relationship in your User model:

use Illuminate\Database\Eloquent\Model;

class User extends Model
    public function orders()
        return $this->hasMany(Order::class);


Step 2: Perform Filtered Aggregation with withSum()

To perform a filtered aggregation on related models, you can use the withSum() method in combination with a where condition. For instance, let's calculate the sum of the "amount" column for orders that have a status of "completed". In your controller or query builder, use the following code:

use App\Models\User;

$usersWithTotalAmount = User::withSum(['orders' => function ($query) {
    $query->where('status', 'completed');
}], 'orders.amount')->get();

In this example, we use the withSum() method and pass an array where the key represents the relationship name ('orders') and the value is a closure that defines the where condition. The 'orders.amount' parameter specifies the column to be summed.


Step 3: Access the Aggregated Data

The $usersWithTotalAmount variable now holds a collection of User models, each with an additional 'orders_amount_sum' attribute representing the sum of the 'amount' column for the filtered orders.

To access the aggregated data, iterate over the collection and retrieve the 'orders_amount_sum' attribute:

foreach ($usersWithTotalAmount as $user) {
    $totalAmount = $user->orders_amount_sum;
    // Do something with the total amount

You can then perform any desired actions with the aggregated data, such as displaying it in your views or performing further calculations.

The withSum() method in Laravel allows you to perform filtered aggregations on related models by applying a where condition. By following the steps outlined in this tutorial, you now have the knowledge to leverage the withSum() method to calculate the sum of specific columns across related models while filtering the results.

Experiment with different relationships, where conditions, and column selections to suit your application's requirements. Laravel's Eloquent provides powerful tools for working with related data and performing data aggregations efficiently.

Happy aggregating related models in Laravel!

Categories : Laravel

Tags : Laravel Laravel 10 withSum() method Eloquent relationships filtered aggregations data aggregation in Laravel

Abhay Dudhatra
Abhay Dudhatra
I am a full-stack developer who is passionate about creating innovative solutions that solve real-world problems. With expertise in technologies such as PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter, and Bootstrap, I love to share my knowledge and help others in the industry through writing tutorials and providing tips. Consistency and hard work are my mantras, and I constantly strive to improve my skills and stay up-to-date with the latest advancements in the field. As the owner of Open Code Solution, I am committed to providing high-quality services to my clients and helping them achieve their business objectives.


Leave a comment

We'll never share your email with anyone else. Required fields are marked *

Related Articles