Reputation: 9766
I am using Laravel 5.2 with Carbon and I trying to get dates in locale format. I mean if I have the date 2015-12-31
in the database, I want it to be printed as 12/31/2015
or 31/12/2015
depends on the user locale.
In the User
model I have an attribute locale
that presents the user locale. But I don't know who to make it works. I know that Laravel using Carbon for dates, but in the Carbon class I see that the format Y-m-d
is hard coded.
I still need the dates will be saved in format Y-m-d
and only the presentation will depends on the User->locale
attribute.
So how can I achieve that behavior? Is there any way to do that with Carbon itself?
Upvotes: 0
Views: 3029
Reputation: 4795
I have solution for you.
Override getAttribute
method in your model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use DateFormatting;
protected $dates = [
'finished_at',
// other field names that you need to format
];
public function getAttribute($key)
{
if ( array_key_exists( $key, $this->getDates() ) ) {
// here you can format your date
}
return parent::getAttribute($key);
}
}
after all you can access to this fields as usual(using magic __get()
)
$model->finished_at;
Upvotes: 1
Reputation: 2922
There is a way to do this using Carbon
but it seems like it's really going to vary according to the specs of your server and what not. From reading, it seems like locale packages aren't always consistent. Use locale -a
on your production server terminal to check which supported locales you have installed. If you need to install one, use sudo locale-gen <NEW LOCALE>
.
But once you have your locale strings sorted out, it seems that you can say
$date = new Carbon;
setlocale('en_GB');
echo $date->formatLocalized('%x'); // '16/06/16'
I derived the %x
modifier from the strftime()
function, it specifies the format to be "the preferred date representation based on locale, without the time" according to the php manual
Upvotes: 1