Laravel 8 group by doesn’t work – fixed
In this tutorial, we will Laravel 8 group by doesn’t work. we just installed Laravel 8 application and we were checking new features and making some examples. And I was working on database group by query, and I getting the following error SQLSTATE[42000]: Syntax error or access violation: 1055 'devnote.users.id' isn't in GROUP BY (SQL: select * from `users` group by `name`)
. And I have query was like as bellow example, and I get all users and group by with name query.
SQLSTATE[42000]: Syntax error or access violation: 1055 ‘devnote.users.id’ isn’t in GROUP BY: This is probably a SQL_MODE problem.
DB Query:
use DB;
$users = DB::table("users")->groupBy("name")->get();
dd($users);
Laravel Eloquent Query
use App\Models\User;
$users = User::groupBy("name")->get();
dd($users);
And when I run a query using database query builder and I getting the below error:
I did not know what is the issue because without group by it was working. I found how to solve it and we have to simply strict mode true to false in the database.php file.
#config/database.php 'strict' => true, TO 'strict' => false, 'connections' => [ 'mysql' => [ 'driver' => 'mysql', 'url' => env('DATABASE_URL'), 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'prefix_indexes' => true, 'strict' => false, 'engine' => null, 'options' => extension_loaded('pdo_mysql') ? array_filter([ PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), ]) : [], ], ],