Search code examples
laravel-5php-carbonarray-map

How to calculate age using carbon in array map function?


This application built in Lavavel 5. I had a table with year of birth value. I query the table using this query:

  $tarikh = DB::table('itemregistrations')
            ->select('itemregistrations.lahir_dd', 'itemregistrations.lahir_mm', 'itemregistrations.lahir_yy')
            ->get();

dd($tarikh); produce this output:

Collection {#709 ▼
#items: array:1123 [▼
0 => {#681 ▼
  +"lahir_dd": 9
  +"lahir_mm": "June"
  +"lahir_yy": 1979
}
1 => {#670 ▶}
2 => {#680 ▶}
3 => {#713 ▶}

I want to calculate the age using carbon and insert into the collection using array map(my earlier code):

 $tarikh->map(function ($detail) {$detail->Umur = "{$detail->lahir_yy}->diffInYears(\Carbon::now())";
        return $detail;
    });

Changed to Ijas suggested code:

  $tarikh->map(function ($detail) {
     $detail->Umur = \Carbon\Carbon::parse($detail->lahir_yy)->diffInYears();
     return $detail;
 });

Solution

  • You can calculate diff as,

    $tarikh->map(function ($detail) {
        $detail->Umur = \Carbon\Carbon::parse($detail->lahir_yy)->diffInYears();
        return $detail;
    });
    

    Updated : Re-generated your results and applied the given solution.

    Fiddle : https://implode.io/i1GanD

    For the given context, This works as you expected.

    The error erased by modifying some code with this:

      $tarikh->map(function ($detail) {
    
            $detail->Umur = \Carbon\Carbon::createFromFormat('Y',$detail->lahir_yy)->diffInYears(); 
    
            return $detail;
        });