Search code examples
laravellaravel-5laravel-query-builder

Getting the unique year value in Laravel


I just wanted to extract unique year value from this date type column. But I always get this error "You might need to add explicit type casts".

enter image description here

If there are 2020-06-23, 2020-07-01, 2019-01-02, 2019-02-05 dates, my desired output is to return the unique year values. So the output should be 2020 and 2019 only.Please help. Thank you.

Here is my code:

$year= DB::table('loans')
            ->select('date_release', DB::raw('YEAR(date_release) as year'))
            ->groupBy('year')
            ->get();

Solution

  • I think that there are only 2 ways to get what you want first you need add another column with name year and store data only year and your query will be like this

    return DB::table('loans')
        ->select('year')->distinct('year');
    

    second one is before return you should some algorithm to extract year and return only distinct year it will be like this

    $year =  DB::table('loans')
        ->select([DB::raw('YEAR(date_release) as year')])
        ->groupBy('year')
        ->value('year');
    $distinct_year = array();
    foreach($year as $item){
        $years = date('Y', strtotime($item->year))
        if(!in_array($years, $distinct_year)){
             array_push($distinct_year, $years);
        }
    }
    return $distinct_year;