CamKode

Laravel Group by Eloquent Relationship

Avatar of Kosal Ang

Kosal Ang

Wed Feb 21 2024

Laravel Group by Eloquent Relationship

In the realm of web development, efficient data retrieval and reporting play a pivotal role in decision-making processes for businesses. Laravel, a popular PHP framework, offers robust tools like the Eloquent ORM (Object-Relational Mapping) for simplifying database interactions. Let's explore how to optimize sales reporting using Laravel's Eloquent ORM.

1use App\Models\Order;
2use Illuminate\Support\Facades\DB;
3
4$vendorOrderTotals = Order::with('product.vendor')
5    ->select('products.vendor_id', DB::raw('SUM(orders.total) as total_sales'))
6    ->join('products', 'orders.product_id', '=', 'products.id')
7    ->groupBy('products.vendor_id')
8    ->get();
9
10foreach ($vendorOrderTotals as $vendorOrderTotal) {
11    echo "Vendor Name: " . $vendorOrderTotal->product->vendor->name . "\n";
12    echo "Total Sales: " . $vendorOrderTotal->total_sales . "\n";
13}
14

The above code snippet demonstrates a common scenario where we fetch sales data grouped by vendors. Let's break down the process step by step:

  1. Fetching Data: We start by querying the Order model along with its related Product and Vendor models using Eloquent's with() method. This ensures that we retrieve all necessary data efficiently, reducing the number of database queries.
  2. Aggregating Sales: To calculate total sales for each vendor, we utilize Laravel's Query Builder alongside raw SQL expressions (DB::raw()) within the select() method. Here, we select the vendor_id from the products table and calculate the sum of total from the orders table, aliased as total_sales.
  3. Joining Tables: We join the orders table with the products table based on the product_id relationship to establish the connection between orders and products.
  4. Grouping Data: Using the groupBy() method, we group the results by vendor_id to aggregate sales data for each vendor.
  5. Retrieving Results: Finally, we retrieve the results using the get() method, obtaining a collection of vendor-wise total sales.
  6. Displaying Results: With the fetched data, we iterate through each vendor's total sales and output the vendor_id along with the corresponding total_sales.

By leveraging Laravel's expressive syntax and powerful ORM capabilities, we've streamlined the process of fetching and aggregating sales data. This not only enhances code readability but also improves performance by minimizing unnecessary database queries.

In conclusion, the utilization of Laravel's Eloquent ORM in conjunction with Query Builder provides developers with a versatile toolkit for handling complex data operations efficiently. Whether it's sales reporting or any other data-driven task, Laravel empowers developers to build robust and scalable solutions with ease.

Related Posts

Mastering Laravel Routing: A Comprehensive Guide

Mastering Laravel Routing: A Comprehensive Guide

Routing is a crucial aspect of any web application, determining how URLs are mapped to controllers and actions

How to sum multiple colums in Laravel collection

How to sum multiple colums in Laravel collection

Are you looking for an example of Laravel collection sum multiple columns. you can see Laravel collection sum two columns.

© 2025 CamKode. All rights reserved

FacebookTwitterYouTube