Juliver Galleto
Juliver Galleto

Reputation: 9037

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?

Upvotes: 2

Views: 4312

Answers (3)

Hari Harker
Hari Harker

Reputation: 791

If you simply want to get one result for every redundant date value in your table, then use the DISTINCT keyword in your query.

Try this if you are using MySql:

select DISTINCT date from events where date IS NOT NULL

Note: DISTINCT considers null value also as a distinct candidate. So, it's advisable to check for null on your where clause.

Also, DISTNCT is faster than Group By.

Upvotes: 2

Depzor
Depzor

Reputation: 1316

The actual query:

SELECT * FROM events GROUP BY date

For Laravel:

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

Upvotes: 2

Chris
Chris

Reputation: 58142

If using Eloqunt, you can use the built in groupBy method:

Events::groupBy('browser')->get();

Upvotes: 1

Related Questions