Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

A more elegant way to get unique years from date column?

Hello,

I have a date column from which I want to get unique years. For example, from the following records:

2022-06-01
2022-07-05
2023-04-12
2020-07-07

I need to get 2020, 2022, 2023.

The way I currently do it is this:

$years = DB::select('SELECT DISTINCT YEAR(date) as year FROM table');

Then it returns an array that looks like:

0 => ["year" => 2020],
1 => ["year" => 2022],
2 => ["year" => 2023],

then in order to iterate over the years I need to do:

foreach ($years as $year)
{
    echo $year->year;
}

and it's too "nested".

Is there a better way to do that?

thanks

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

add ->pluck('year')

1 like
Ligonsker's avatar

@Snapey thanks, but I get error "pluck on array", I guess because I'm using raw SELECT?. How can I convert the query above to Laravel's query builder?

Update: I edited the query:

$years = DB::table('table')->select(DB::raw('SELECT DISTINCT YEAR(date) as year')->pluck('year');

and this time it works

Please or to participate in this conversation.