Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. now I want to use that data with some carbon function in Laravel view.

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"

How can I do this?

like image 744
sasy Avatar asked Feb 02 '16 09:02

sasy


2 Answers

It works with global namespace to my view.blade.php as

      {{ \Carbon\Carbon::parse($row->posted_at)->diffForHumans() }}
like image 184
Kabir Hossain Avatar answered Sep 24 '22 03:09

Kabir Hossain


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.

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
like image 34
naneri Avatar answered Sep 22 '22 03:09

naneri