简体   繁体   English

"在 laravel 视图中使用碳函数(刀片模板)"

[英]use carbon function in laravel view(Blade template)

I get some values from the database and I passed those values into view from the controller<\/strong> .我从数据库中获取了一些值,并将这些值从控制器<\/strong>传递到视图中。 now I want to use that data with some carbon function<\/code> in Laravel view<\/strong> .现在我想在Laravel 视图<\/strong>中使用带有一些carbon function<\/code>的数据。

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;


}

它与我的 view.blade.php 的全局命名空间一起使用

      {{ \Carbon\Carbon::parse($row->posted_at)->diffForHumans() }}

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

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 {
  ...
}

Faced same issue and this is what worked for me面临同样的问题,这对我有用

$create = $time->created_at;

$create_at_difference = Carbon\Carbon::createFromTimestamp(strtotime($create))
                    ->diff(\Carbon\Carbon::now())->days;

Use blade injections for the cleanest result.使用刀片注射以获得最干净的结果。 Example:例子:

@inject('carbon', 'Carbon\Carbon')
...
<span>{{ $carbon::parse($model->created_at) }}</span>

不要重复\\Carbon\\Carbon ,只需尝试

\\Carbon::createFromTimestamp(strtotime($create))->diff(\\Carbon::now())->days

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM