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

SlimPickins's avatar

Help transforming MySQL query

Hi all, I'm still learning the ropes with Laravel, Eloquent and such. I can't seem to work out how to get this to run in Laravel.

select asset.assetmake_id as 'Make Id', assetmake.name as 'Name', count(*) as 'Count' from asset inner join assetmake on assetmake.ID=asset.assetmake_id group by assetmake_id order by Count desc;

I've tried variants of this:

DB::table("asset") ->join("assettype", "assettype.id", "=", "asset.assettype_id") ->select("asset.assettype_id as 'type id'", "assettype.name as 'name'", "count ()") ->orderBy("count ()","desc") ->groupBy("assettype_id") ->get();

And I've tried a DB::raw query but had no luck with that either. Any help would be appreciated.

Cheers.

0 likes
3 replies
SlimPickins's avatar

Sorry, the copy/paste made a mess of the formatting there by the looks of it.

SlimPickins's avatar
SlimPickins
OP
Best Answer
Level 2

Got it. Looks like this:

$types = \DB::table("asset") ->join("assettype", "assettype.id", "=", "asset.assettype_id") ->selectRaw('asset.assetmake_id as "MakeId", COUNT(*) as "Count"') ->whereNotNull('asset.assetmake_id') ->groupBy("MakeId") ->orderBy('Count', 'DESC') ->take(10) ->get();

Please or to participate in this conversation.