Saliou MBALO
Saliou MBALO

Reputation: 169

Laravel 5 date Format value

I would like to know why my code is not working. I have my model Organigramme i want to calculate with a function the age between two dates:

public function getAncienneteAttribute()
{
    $now = Carbon::now();

    $date_dentree = Carbon::createFromFormat('d/m/Y', $this->date_dentree);

        return $now->diffInYears($date_dentree);

}

But I'm faced this error: Data missing Someone can help me please.

Upvotes: 1

Views: 89

Answers (2)

VIKAS KATARIYA
VIKAS KATARIYA

Reputation: 6005

Try this

$date_dentree = \Carbon\Carbon::createFromFormat('Y-m-d', $this->date_dentree);
$diffYears = \Carbon\Carbon::now()->diffInYears($date_dentree );

//\Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $request->date)->format('Y-m-d')

$dbDate = \Carbon\Carbon::parse('2020-05-10');
$diffYears = \Carbon\Carbon::now()->diffInYears($dbDate);

Upvotes: 1

Silidrone
Silidrone

Reputation: 1581

Your $this->date_dentree format is not matching the format you passed to Carbon::createFromFormat, it is probably the default format so try the code below:

public function getAncienneteAttribute()
{
    $now = Carbon::now();
    return $now->diffInYears(new Carbon($this->date_dentree));
}

Upvotes: 1

Related Questions