I am new to laravel. I am working on a project with a lots of datetime values that would be display on the UI. In Code Igniter I use to create a function like below and put in a helper directory and make available in my app.
function datetime_to_text($datetime){
return date('j F Y, g:i a', strtotime($datetime));
}
How can I make such a function available globally in laravel 5 (Able to access in both my views and controllers)
Datetimes in Laravel are converted to Carbon
objects.
Carbon is a wonderful library.
By default, created_at
, updated_at
, and deleted_at
are automatically converted for you. If you have other DATETIME columns in your table, you simply need to add them to the $dates
array in your Eloquent model:
class User {
protected $dates = ['logged_in_at'];
}
http://laravel.com/docs/5.1/eloquent-mutators#date-mutators
Now when you echo $object->created_at
, it calls the Carbon __toString()
method. You can set a default format with:
Carbon::setToStringFormat('j F Y, g:i a');
Or you can easily format things with
echo $object->created_at->format('j F Y, g:i a');
It's maybe helpful for CodeIgniter experts:
You can create a file in app/Helpers/
(with making Helpers
directory)
like: app/Helpers/
HelperClass.php
<?php
namespace App\Helpers;
use Carbon\Carbon;
class HelperClass{
public static function updatedOn($updated_at)
{
return 'Last updated '. $updated_at->diffForHumans();
}
}
Now you've to add this HelperClass
in config/app.php
'aliases' => [
...,
'HelperClass' => 'App\Libraries\HelperClass'
]
Now just call in your view page:
<div class="col-md-12">
{!! HelperClass::updatedOn($data->updated_at) !!}
</div>
Output like: Last updated 5 minutes ago.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.