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

ethar's avatar
Level 5

1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column

i have chat_msgs table it contains ( body, type, from_id, to_id, )

i want to group by from_id, my Eloquent

    public function index()
    {
        $chatMsgs=ChatMsg::select('id','body','from_id','to_id')
            ->where('to_id',Auth()->user()->id)
            ->with('user:id,name')
            ->groupBy('from_id')
            ->get();
        return $chatMsgs;
    }

but I got this error SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'mhpss.chat_msgs.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select id, body, from_id, to_id from chat_msgs where to_id = 1 group by from_id)

I try to use

public function index()
{
    $chatMsgs=ChatMsg::select('id','body','from_id','to_id')
        ->where('to_id',Auth()->user()->id)
        ->with('user:id,name')
        ->groupBy('from_id','id')
        ->get();
    return $chatMsgs;
}
but I got all record without groubing
0 likes
5 replies
Tray2's avatar

Group by is used when you want to group data by columns so you can performs an aggregate function on one of the columns.

For example

SELECT artist, COUNT(record_name) AS no_of_records
FROM records
GROUP BY artist

Since you are not using an aggregate remove the group by.

sr57's avatar

Where you use group your select can only contain group fields (here : from_id', id )

newbie360's avatar

your error is about if the table have two row 'from_id' has same value, MySQL don't know which row you want

there can use MIN(id) or MAX(other_column) or ANY_VALUE(column)

but in your OP code, just want to groupBy, so we don't know what you want to do

newbie360's avatar

make an example

id | name  | rating | country_code
----------------------------------
1  | Adm   | 2      |33
3  | Joe   | 5      |33

SELECT MAX(id), MIN(name), ANY_VALUE(rating)
FROM table
GROUP BY country_code

the result is

id | name  | rating | country_code
----------------------------------
3  | Adm   | 5      |33

ANY_VALUE() means follow the id column

Please or to participate in this conversation.