Level 122
add ->pluck('year')
1 like
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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
add ->pluck('year')
Please or to participate in this conversation.