Search code examples
phplaravelphp-carbon

Laravel carbon failed to parse time string


I need to select users with specific age from model User, but have this error:

DateTime::__construct(): Failed to parse time string (birth) at position 0 (b): The timezone could not be found in the database 

part of controller:

$users = User::where(Carbon::parse('birth')->diff(Carbon::now())->format('%y'), '>=', 18)->get();

when i use it in view all working fine:

 @foreach ($userss as $user)

 <?php  $age_year = Carbon::parse($user->birth)->diff(Carbon::now())->format('%y'); ?>


@endforeach

Thanks for answers!


Solution

  • In your controller example, you are trying to parse the string 'birth' instead of the database field 'birth'.

    Since you are returning a collection, just run through the returned collections with the filter() method before sending it down to your view. You can also use the age property instead of doing a diff

    $users = User::get()->filter(function($user, $key) {
        return (Carbon::parse($user->birth)->age >= 18);
    });
    

    I did not test this, so you may get some typos, but this is how you will want to accomplish this task.