Try with query builder
$logs = DB::table('callLog')
->groupBy('caller')
->get();
https://laravel.com/docs/5.3/queries#ordering-grouping-limit-and-offset
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
So I'm trying to get a "top list" from my call log table it has "caller", "callee" and "duration" rows, what I want is to get like top 3 who made most calls in last 24 hours. I tried
CallLogModel::groupBy('caller')->get()
But groupBy is returning
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
So I guess my question is - is there another way to get that "top X" list from eloquent model? Thanks.
In MySQL 5.7, the sql mode ONLY_FULL_GROUP_BY is enabled by default, which means your select list must be in your aggregate functions (GROUP_BY, HAVING) assuming they are functionally dependent. See (seriously): https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html
This will work:
CallLogModel::selectRaw('count(*) AS cnt, caller')->groupBy('caller')->orderBy('cnt', 'DESC')->limit(5)->get();
This will not:
CallLogModel::selectRaw('count(*) AS cnt, caller, callee')->groupBy('caller')->orderBy('cnt', 'DESC')->limit(5)->get();
If caller isn't functionally dependent on caller (and it wouldn't be), you can do this:
CallLogModel::selectRaw('count(*) AS cnt, caller, ANY_VALUE(callee)')->groupBy('caller')->orderBy('cnt', 'DESC')->limit(5)->get();
Or, again, disable ONLY_FULL_GROUP_BY. There is some other stuff out there if you want to read further about the pros/cons of leaving ONLY_FULL_GROUP_BY enabled. For most cases, it's probably fine to disable. Just keep it in the back of your mind as you write are verify your query results.
Please or to participate in this conversation.