laraveldatelaravel-5casting

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')


Solution

  • 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';