What Is Date Serialization In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

When building JSON APIs, you will often need to convert your models and relationships to arrays or JSON. Eloquent includes convenient methods for making these conversions, as well as controlling which attributes are included in your serializations. and In Date Serialization - Customizing The Date Format Per Attribute. so today we are going to discuss about date serialization.

What Is Date Serialization In Laravel With Example

Date Serialization

Customizing The Default Date Format

You may customize the default serialization format by overriding the serializeDate method:

 

protected function serializeDate(DateTimeInterface $date)
{
    return $date->format('Y-m-d');
}
 

iCustomizing The Date Format Per Attribute

You may customize the serialization format of individual Eloquent date attributes by specifying the date format in the cast declaraton:

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

To know more about cast declaration visit our bajarangisoft site.

Related Post