Laravel carbon failed to parse time string

本小妞迷上赌 提交于 2019-12-11 15:57:24

问题


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!


回答1:


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.




回答2:


try this:

User::where('birth','>=', Carbon::now()->subYears(18)->toDateTimeString());

not tested yet, but hope it works!




回答3:


You can use Carbon's diff helper to calculate age, and filter method to filter objects(User in this case).

$users = User::get()->filter($user, $key) {
    return Carbon\Carbon::now()->diff($user->birth)->y >= 18;
});

There are also other helpers functions available with Carbon, some are:

// diffInYears(), diffInMonths(), diffInWeeks()
// diffInDays(), diffInWeekdays(), diffInWeekendDays()
// diffInHours(), diffInMinutes(), diffInSeconds()

Please review this for more information: http://carbon.nesbot.com/docs/



来源:https://stackoverflow.com/questions/45649128/laravel-carbon-failed-to-parse-time-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!