How use carbon in Laravel 5.2 application-wide
Asked Answered
P

3

6

How to use Carbon in Laravel 5.2 without use Carbon\Carbon; added in every View and Controller..?

Particularly answered 14/3, 2016 at 23:2 Comment(2)
No it's not added to every View or Controller. If you need to use Carbon functions you need to include with use!Devastate
scotch.io/tutorials/…Clingfish
F
21

Add the following line to the aliases array in the config/app.php:

'Carbon' => 'Carbon\Carbon'

And you need to add use Carbon; every class where you want to use it.

Finesse answered 14/3, 2016 at 23:14 Comment(2)
Infact i can alias it just fine and call it afterwards like \Carbon, but the autocomplete goes to hell :)Particularly
scotch.io/tutorials/…Clingfish
M
2

You can declare some fields in your models using the following structure:

protected $dates = ['created_at', 'updated_at', 'disabled_at','mydate'];

All of those fields will automatically be Carbon instances and you will be able to use them in your views like:

{{ $article->mydate->diffForHumans() }}

This is the answer I provided some time ago here.

And here is the documentation from Laravel for that

Marplot answered 14/3, 2016 at 23:9 Comment(5)
In order to use ->diffForHumans() function doesn't he have to include "use Carbon/Carbon"?Devastate
not if he declares the protected $dates properties in his models :)Marplot
The tips are great yeah, and thanks to the laravel team :)Particularly
Yep, thanks to the Laravel team, I'm just copy pasting here hahaMarplot
scotch.io/tutorials/…Clingfish
D
0

Here's what I have on my helpers.php

function myCarbon($date)
{
  return $date != '' ? \Carbon\Carbon::parse($date) : '-';
}

Then on any controllers and views:

myCarbon($model->field)->format('F d, Y');

And since I usually have mm/dd/yyyy and mm/dd/yyyy H:i on my blades, I have these on my helper file:

function mydateFormat($date)
{
  return $date != '' ? myCarbon($date)->format('m/d/Y') : '-';
}

function mytimeFormat($date)
{
  return $date != '' ? myCarbon($date)->format('H:i') : '-';
}

function mydateTime($date)
{
  return $date != '' ? myCarbon($date)->format('m/d/Y H:i') : '-';
}

Now you can use this application-wide on any controllers and views.

(note: function names are sample only, not what actually I am using, change based on your need)

Danzig answered 8/8, 2019 at 5:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.