Code Demon Code Demon - 3 months ago 9
MySQL Question

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

Is there a way I could retrieve only one record from

date
records with the
same
value 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. 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