Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Maged's avatar
Level 6

Query reports and group by user and count certain field

I have this report migration

$table->unsignedInteger('user_id')->unsigned()->nullable()->index();
$table->string('reason'); // can be one of three values, say ('bad, 'good', 'something')

i want now to display a table where i have the user and column for each reason counting how many times he got records on this

user | bad | good | something
Jeffrey | 3 | 10 | 2

how to query this one ? and have a collection where i can loop and display rows in table :)

0 likes
3 replies
jlrdw's avatar

I don't know all your data, but a basic groupby, count goes like this example:

$quy = Powner::query()->leftJoin('dc_pets', 'dc_powners.ownerid', '=', 'dc_pets.ownerid')
                ->select('dc_powners.ownerid', 'dc_powners.oname')
                ->selectRaw('count(dc_pets.petid) as countOfPets')
                ->groupby('dc_powners.ownerid')
                ->orderby('dc_powners.oname')
                ->get();

Results basically give:

ownerid, oname, countOfPets

Like:

5|Bob|3
4|Greg|9
2|Rob|1

So in example, Greg, user id 4 as 9 pets in the related table. But just example and suggestion, adapt as needed.

Also lookup aggregate functions:

https://laravel.com/docs/8.x/queries#aggregates

1 like
SilenceBringer's avatar
Level 55

@maged something like

User::join('reports', 'users.id', 'reports.user_id')
	->select(
		'users.*',
		DB::raw('sum(if(reason = "bad", 1, 0)) as bad'),
		DB::raw('sum(if(reason = "good", 1, 0)) as good'),
		DB::raw('sum(if(reason = "something", 1, 0)) as bsomethingad')
	)
	->groupBy('users.id')
	->get()
1 like

Please or to participate in this conversation.