2

我在 Laravel 4.x 论坛上问过这个问题,并试图在谷歌上找到答案,但没有任何运气。

我正在使用 Eloquent 加载一堆具有created_at属性的用户对象。默认的 MySQL 时间戳不是很可读,所以我认为readableDate()向我的 User 模型添加一个方法会很巧妙,它会将值输出为“1 分钟前”、“2 天前”。

当我在刀片模板中调用该方法时,例如:$user->readableDate()我得到了所需的输出,但我的整个布局被破坏了。

是这样,还是应该可以从模板中调用模型方法?

4

4 回答 4

3

If you're using Laravel's Eloquent models, you do not need to add custom methods for handling dates. By default, date fields such as created_at and updated_at are handled as a Carbon objects, which allows you to display the date in a human readable format:

{{ $user->created_at->diffForHumans() }}

You can add additional date fields to your Eloquent model with the getDates() method.

于 2013-11-18T15:43:51.720 回答
2

是的,blade 被编译为 PHP。:)

你只需要:

将您的用户传递给您的视图:

 return View::make('showUser')->with('user', $user);

然后使用它:

<hml><body>

    Last update: {{ $user->readableDate() }}

</body></hml>
于 2013-05-31T08:13:32.323 回答
0

我可以假设您将其包装在刀片标签 {{ code here }} 中,还是您错过了那部分?

此外,您的模型应该使用如下静态方法调用:

{{ User::readableDate() }}
于 2013-05-31T08:11:29.697 回答
0

好的,我想通了。我试图做的是可能的,但它抛出了一个我看不到的错误。当我查看页面的源代码时,通常的 laravel 错误 HTML 在我的输出下方。created_at 字段中的默认值会引发错误。

于 2013-05-31T09:34:29.337 回答