Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To count the relationship column in Laravel using GroupBy, you can use the following code:

$counts = YourModel::with('relationship')->select('relationship_id', \DB::raw('COUNT(*) as total'))->groupBy('relationship_id')->get();

Explanation: 1. You start by calling the with() method to load a relationship with your model. 2. Next, you use the select() method to select the relationship column you want to group by and a raw query to count the occurrences of each relationship ID column. 3. Then, you use the groupBy() method to group the counts by the relationship column. Finally, you call the get() method to retrieve the count data.

This will return an array of objects, each containing the relationship column and the count of its occurrences. You can access the count for a specific relationship by using $counts->total attribute of the object.