Laravel Grouping by Eloquent Relationship

yudijohn picture yudijohn · Apr 7, 2016 · Viewed 41.1k times · Source

How can I group by relation?

Example

Sales::with('product_detail.product')->groupBy('product_name')->get()

How can I get a result with eloquent code?

Answer

Imtiaz Pabel picture Imtiaz Pabel · Apr 7, 2016

You can specify a callback function for grouping your relation like this:

Sales::with(['product_detail.product' => function($query){
        $query->groupBy('product_name');
    }])->get();