Sayantan Das
Sayantan Das

Reputation: 1641

How do I count the number of unique rows in group by laravel?

I have three notifications type, TYPE_A TYPE_B TYPE_C. For each type there could be multiple notifications for a single user. I want to get the number of notifications a user got for each of the notification types. For now I have this:

$notifications = Notification::where('user_id', $user->id)->groupBy('notification_type')->get();

How do I count the number of rows each notification_type has?

Upvotes: 0

Views: 234

Answers (1)

Amit Gupta
Amit Gupta

Reputation: 17668

You can use raw() method as:

$notifications = Notification::where('user_id', $user->id)
            ->select('*', DB::raw("count(*) as count"))
            ->groupBy('notification_type')
            ->get();

Upvotes: 1

Related Questions