LARAVEL · 5 APR 2021 · 2 MIN READ

GROUP BY issues in Laravel / Eloquent

Here is a little trick to solve a problem that took me quite a while to solve in an “elegant” way:

If, when you test on your local environment, a GROUP BY in a SQL query with Eloquent works in your Laravel application — one where you don’t include all your select fields — and you need that behaviour to work on a hosting in a production environment, where you normally cannot control the configuration of the MySQL/MariaDB databases, this simple trick should work for you and make these queries run without problems:

Open the config/database.php file of your Laravel application and, in the MySQL section, right below ‘strict’ => true, add the following:

'modes' => [
//'ONLY_FULL_GROUP_BY', // Disable this to allow grouping by one column
'STRICT_TRANS_TABLES',
'NO_ZERO_IN_DATE',
'NO_ZERO_DATE',
'ERROR_FOR_DIVISION_BY_ZERO',
'NO_AUTO_CREATE_USER',
'NO_ENGINE_SUBSTITUTION'
],

This will make Laravel not require all the select variables to be in the group by, and this type of query will work perfectly for you.

I hope it helps you solve this problem, which cost me so much to solve without setting the strict variable in this file to false, as many forums suggested — a quick fix, but one that can leave your application in an ugly situation against a database, with anomalous behaviour of your operations against it on your hosting.

Is this happening on a project in production?

We audit and fix WordPress and Laravel installations every week.

Let’s talk
Scroll to Top