laravel 在刀片模板中调用 Model->Method()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16852626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:50:38  来源:igfitidea点击:

Calling Model->Method() within blade templates

laravellaravel-4

提问by Mcg1978

I asked this on the Laravel 4.x forum and tried to find the answer on Google without any luck.

我在 Laravel 4.x 论坛上问过这个问题,并试图在没有任何运气的情况下在 Google 上找到答案。

I'm using Eloquent to load a bunch of user objects that have a created_atproperty. The default MySQL timestamp isn't very readable, so I thought it would be neat to add a readableDate()method to my User model which would output the value as "1 minute ago", "2 days ago" instead.

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

When I call on the method in my blade templates like: $user->readableDate()I get the desired output but my whole layout is broken.

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

Is it, or should it be possible to call on a model method from within a template?

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

回答by Kirk Beard

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_atand updated_atare handled as a Carbon objects, which allows you to display the date in a human readable format:

如果您使用 Laravel 的 Eloquent 模型,则无需添加自定义方法来处理日期。默认情况下,诸如created_at和 之updated_at类的日期字段作为Carbon 对象处理,这允许您以人类可读的格式显示日期:

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

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

您可以使用该方法向 Eloquent 模型添加额外的日期字段getDates()

回答by Antonio Carlos Ribeiro

Yes, blade is compiled to PHP. :)

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

You just have to:

你只需要:

Pass your user to your view:

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

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

And then use it:

然后使用它:

<hml><body>

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

</body></hml>

回答by Mcg1978

ok, I figured this out. What I was trying to do is possible but it was throwing an error that I couldn't see. When I viewed the source of the page the usual laravel error HTML was below my output. The error was being thrown by default values in the created_at field.

好的,我想通了。我试图做的事情是可能的,但它抛出了一个我看不到的错误。当我查看页面的源代码时,通常的 Laravel 错误 HTML 低于我的输出。该错误是由 created_at 字段中的默认值引发的。

回答by Johnny

Can I assume you are wrapping it inside blade tags {{ code here }}, or did you miss that part?

我可以假设您将它包裹在刀片标签 {{ 此处为代码 }} 中,还是您错过了那部分?

Also, your model should be called using the static approach like this:

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

{{ User::readableDate() }}