Laravel Carbon无法解析时间字符串 [英] Laravel carbon failed to parse time string

查看:288
本文介绍了Laravel Carbon无法解析时间字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从用户"模型中选择具有特定年龄的用户,但是出现此错误:

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

控制器的一部分:

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

当我将其用于查看时一切正常:

 @foreach ($userss as $user)

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


@endforeach

感谢答案!

解决方案

在您的控制器示例中,您尝试解析字符串'birth'而不是数据库字段'birth'.

由于您要返回一个集合,因此只需使用filter()方法遍历返回的集合,然后再将其发送到视图中即可.您也可以使用 age 属性,而不是进行差异

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

我没有对此进行测试,因此您可能会遇到一些错别字,但这就是您要完成此任务的方式.

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!

解决方案

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.

这篇关于Laravel Carbon无法解析时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆