在 Laravel 视图中使用 carbon 函数(Blade 模板)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35149189/
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
use carbon function in laravel view(Blade template)
提问by sasy
I get some values from the database and I passed those values into view from the controller. now I want to use that data with some carbon function
in Laravel view.
我从数据库中获取一些值,然后将这些值从控制器传递到视图中。现在我想carbon function
在Laravel 视图中使用这些数据。
In my View file I wrote
在我的视图文件中,我写了
foreach($customer as $time){
$create= $time->created_at;
$update= $time->updated_at;
$create_at_difference=\Carbon\Carbon::createFromTimestamp(strtotime($create))->diff(\Carbon\Carbon::now())->days;
}
when I try like this it returns "Class 'Carbon' not found"
当我这样尝试时它会返回 "Class 'Carbon' not found"
How can I do this?
我怎样才能做到这一点?
回答by Kabir Hossain
It works with global namespace to my view.blade.php as
它与我的 view.blade.php 的全局命名空间一起使用
{{ \Carbon\Carbon::parse($row->posted_at)->diffForHumans() }}
回答by naneri
If you want to use the namespaced class, you don't need the first slash:
如果要使用命名空间类,则不需要第一个斜杠:
$create_at_difference=Carbon\Carbon::createFromTimestamp(strtotime($create))->diff(\Carbon\Carbon::now())->days;
You should just write Carbon\Carbon instead of \Carbon\Carbon.
你应该只写 Carbon\Carbon 而不是 \Carbon\Carbon。
That is a quick solution. But, using classes directly in your views is a bad idea. You can add more functionality to your model by creating a function that will return current created at difference.
这是一个快速的解决方案。但是,直接在视图中使用类是个坏主意。您可以通过创建一个函数来为您的模型添加更多功能,该函数将返回在不同时创建的电流。
lets say you have Customer model, you can go that way:
假设您有客户模型,您可以这样做:
use Carbon\Carbon;
class Customer extends Eloquent
{
public function created_at_difference()
{
return Carbon::createFromTimestamp(strtotime($this->created_at))->diff(Carbon::now())->days;
}
}
then in the view you can access this like:
然后在视图中,您可以像这样访问:
@foreach($customers as $customer)
{{$customer->created_at_difference()}}
@endforeach
回答by Qazi
Do not repeat \Carbon\Carbon
, just try
不要重复\Carbon\Carbon
,只是尝试
\Carbon::createFromTimestamp(strtotime($create))->diff(\Carbon::now())->days
\Carbon::createFromTimestamp(strtotime($create))->diff(\Carbon::now())->days
回答by Вилислав Венков
Another option, i think it's better put this line of code on top of your class:
另一种选择,我认为最好将这行代码放在您的班级之上:
namespace App\Http\Controllers
use Carbon\Carbon;
class MyController {
...
}