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
CodePudding user response:
You can try this: distinct() will get the distinct 'serial_number'
Products::where('depart_id', $depart_id)
->where('serial_number', "")
->distinct();
CodePudding user response:
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.
