Laravel - Mutators / Casts - Date Casting

By default, Eloquent will cast the created_at and updated_at columns to instances of Carbon, which extends the PHP DateTime class and provides an assortment of helpful methods. You may cast additional date attributes by defining additional date casts within your model's $casts property array. Typically, dates should be cast using the datetime or immutable_datetime cast types.

When defining a date or datetime cast, you may also specify the date's format. This format will be used when the model is serialized to an array or JSON:

    
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'created_at' => 'datetime:Y-m-d',
    ];
	

When a column is cast as a date, you may set the corresponding model attribute value to a UNIX timestamp, date string (Y-m-d), date-time string, or a DateTime / Carbon instance. The date's value will be correctly converted and stored in your database.

You may customize the default serialization format for all of your model's dates by defining a serializeDate method on your model. This method does not affect how your dates are formatted for storage in the database:

    
    /**
     * Prepare a date for array / JSON serialization.
     *
     * @param  \DateTimeInterface  $date
     * @return string
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d');
    }
	

To specify the format that should be used when actually storing a model's dates within your database, you should define a $dateFormat property on your model:

    
    /**
     * The storage format of the model's date columns.
     *
     * @var string
     */
    protected $dateFormat = 'U';