Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: how to set date format on model attribute casting?

I have in model:

protected $casts = [     'date' => 'date', ]; 

Does laravel have some ability to set cast format, something like:

protected $casts = [     'date' => 'date_format:d/m/yyyy', ]; 

?

EDITED

I tried this:

In model:

protected $dateFormat = 'm/d/Y';  protected $dates = ['driver_expiration', 'created_at', 'updated_at', 'deleted_at'];  protected $casts = [     'driver_expiration'     => 'date', ]; 

I saved date(driver_expiration) as '01/012016' but date is saved 0000-00-00.

laravel documentation: https://laravel.com/docs/5.1/eloquent-mutators Tell us $dateFormat works only for timestamps ('created_at', 'updated_at', 'deleted_at')

like image 778
fico7489 Avatar asked Jun 16 '16 11:06

fico7489


People also ask

What is $cast in laravel?

From Laravel Documentation: Attribute Casting The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to.

How does laravel store dates?

You can use Carbon\Carbon::parse($date); and then pass the Carbon object to eloquent model. I have date like '02 jul 2019' in My data input.


1 Answers

After laravel 5.6,

You can individually customize the format of Eloquent date and datetime casting:

protected $casts = [     'birthday'  => 'date:Y-m-d',     'joined_at' => 'datetime:Y-m-d H:00', ]; 

This format is used when the model is serialized to an array or JSON data

like image 81
Hemerson Varela Avatar answered Sep 30 '22 05:09

Hemerson Varela