In Laravel development, it's common to need to filter and sum a column from a database table. Fortunately, Laravel provides the simple `sum()` function to help us achieve this efficiently.
The `sum()` function is used to sum all data in a specific column. For example, to sum the `price` column in the `orders` table, you can use the following code:
$totalPrice = DB::table('orders')->sum('price');
This code will return the total sum of all order prices in the `orders` table.
Sometimes, you might want to sum a column under specific conditions. For instance, if you want to calculate the total price of completed orders, you can use the following code:
$totalPrice = DB::table('orders')
->where('status', '=', 'complete')
->sum('price');
This code will return the total price of all completed orders in the `orders` table.
In some cases, you may need to group a column by multiple conditions and sum the data within each group. For example, to calculate the total order price for each customer, you can use the following code:
$orderTotals = DB::table('orders')
->select(DB::raw('customer_id, sum(price) as total_price'))
->groupBy('customer_id')
->get();
The above code will return an array where each element contains a customer ID and their total order amount.
After running the code, the returned data might look like this:
Array
(
[0] => stdClass
(
[customer_id] => 1
[total_price] => 500
)
[1] => stdClass
(
[customer_id] => 2
[total_price] => 750
)
[2] => stdClass
(
[customer_id] => 3
[total_price] => 250
)
)
The `sum()` function in Laravel allows us to easily sum a column's data. Additionally, by using the `where()` function, we can sum data under specific conditions; and with the `groupBy()` function, we can group and sum data across multiple conditions. Mastering these essential database query techniques can significantly improve development efficiency.