I'm trying to get the most recent record for a single customer on a table. Example:
ID Customer City Amount
1 Cust001 City1 2
2 Cust001 City2 3
3 Cust001 City1 1
4 Cust001 City2 1
5 Cust001 City2 3
6 Cust001 City3 1
7 Cust001 City3 1
8 Cust002 City1 2
9 Cust002 City1 1
10 Cust002 City2 3
11 Cust002 City1 2
12 Cust002 City2 1
13 Cust002 City3 2
14 Cust002 City3 3
15 Cust003 City1 1
16 Cust003 City2 3
17 Cust003 City3 2
Please note that the table also has created_at and updated_at fields. I omitted those fields for simplicity.
In the end I want my query to return for Cust001:
ID Customer City Amount
3 Cust001 City1 1
5 Cust001 City2 3
7 Cust001 City3 1
And for Cust002:
ID Customer City Amount
11 Cust002 City1 2
12 Cust002 City2 1
14 Cust002 City3 3
I've tried:
Table::where('Customer', 'Cust001')
->latest()
->groupBy('City')
->get()
and also
Table::select(DB::raw('t.*'))->from(DB::raw('(select * from table where Customer = \'Cust001\' order by created_at DESC) t'))
->groupBy('t.City')->get();
But it keeps returning the oldest record on each group (and I want the most recent).
How can I achieve this? If is easier for you guys, you can write the SQL Query here and I will find a way to "translate it" to Laravel syntax.