Home » Php » php – Calculate age in a list with Laravel

php – Calculate age in a list with Laravel

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a list of users, where each user has “N” pets and one of the attributes is the Pet’s birth date. How can I take that date of birth of the animal that is in a List and calculate the age and present it in the List?

public function index()
    {
        $pets =  Auth::user()->pets()->get();      
        return view('auth.pets.list',compact('pets'));        
    }
How to&Answers:

age calculation by using Laravel carbon.

use Carbon\Carbon;

$dateOfBirth = '1994-07-02';
$years = Carbon::parse($dateOfBirth)->age;

As per your code.

@if(!empty($pets))
    @foreach($pets as $pet)
        {{ Carbon::parse($pet->date_birth)->age ?? 0 }} years
    @endforeach
@endif

Answer:

To directly show age in your view you can use this:

\Carbon\Carbon::parse($pet->date_birth)->diff(\Carbon\Carbon::now())->format('%y years, %m months and %d days');

Reference:
Calculate Age from date stored in database in Y-m-d using Laravel 5.2