Code Demon Code Demon - 4 months ago 9
MySQL Question

get only one record from a same date records in the collection Laravel

Is there a way I could only retrieved only one record from a same date records in the collection?

My records goes like this,

id | date | event_name | type
----------------------------------------
1 | 2016-01-23 | event 1 | event 1
2 | 2016-01-23 | event 1 | event 2
3 | 2016-03-15 | event 2 | event 1
4 | 2016-03-15 | event 2 | event 2


so as you can see, there are records with same date and I want to fetch only one on that same date records, so I expect to get,

2016-01-23, event 1
2016-03-15, event 2


I tried,

$events = events::select( events.*',
DB::raw('(select date from events where date = events.date) as events'))
->get();


but unfortunately its not working like it gives me an empty array from

dd(var_dump($events->toArray()));


any ideas, help please?

Answer

The actual query:

SELECT * FROM events GROUP BY date

For Laravel:

$events = DB::table('events')->groupBy('date')->get(); 
Comments