Skip to content
Advertisement

Select the distinct latest records based on their creation date

How can I select, preferably using eloquent laravel’s query builder, the latest distinct records from a table.

I have tried this query without success.

 Products::where('depart_id', $depart_id)
                ->distinct("serial_number")
                ->latest()
                ->where('serial_number', ""); // get one of the distinct products

Advertisement

Answer

The solution was to use

 Products::where('depart_id', $depart_id)
                ->distinct('serial_number')
                ->orderBy('serial_number', 'desc')
                ->orderBy('created_at', 'desc')
                ->where('serial_number', "serial_number");

This ensured that the distinct returned only the unique latest record of each value.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement