我有一个用户列表,其中每个用户都有“ N”只宠物,属性之一是宠物的出生日期。如何获取列表中动物的出生日期并计算年龄并将其显示在列表中?
public function index()
{
$pets = Auth::user()->pets()->get();
return view('auth.pets.list',compact('pets'));
}
使用Laravel碳的年龄计算。
use Carbon\Carbon;
$dateOfBirth = '1994-07-02';
$years = Carbon::parse($dateOfBirth)->age;
根据您的代码。
@if(!empty($pets))
@foreach($pets as $pet)
{{ Carbon::parse($pet->date_birth)->age ?? 0 }} years
@endforeach
@endif
要直接在您的视图中显示年龄,您可以使用此:
\Carbon\Carbon::parse($pet->date_birth)->diff(\Carbon\Carbon::now())->format('%y years, %m months and %d days');