Laravel: how to set date format on model attribute casting?
Instead of casting a date format, you can use mutators to set the format you like:
For example, if your column was called date
, you can add the following function to your model:
public function setDateAttribute( $value ) {
$this->attributes['date'] = (new Carbon($value))->format('d/m/y');
}
The setDateAttribute
is always in the format set[ColumnName]Attribute
, using CamelCase. The date
in the $this->attributes['date']
part must also match your actual column name in the table.
When you create
or update
a record in your database, the format will automatically be changed by the function above.
Note: You may need to add the use Carbon\Carbon
statement to the top of your Model to use the Carbon library.
Take a look at other examples here.
UPDATE
Optionally, you can define a format for date
columns using:
protected $dateFormat = 'Y-m-d';
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