Casting attributes to given types is really useful, could apply to external transformers and such. Could be used in dynamic API documentations and in cases you use Laravel methods like collection->toArray() and such.


Using protected $casts is really useful when you want to set-up a reusable casting for all the instances of your Eloquent model.

Casting dates there is fun and all, just a reminder if you use the Eloquent model itself for cases such as views and whatelse the attribute will come in Carbon object format to string (Y-m-d H:i:s) for example if the database serves a timestamp.

protected $casts = [
    'mydateattribute' => 'date:Y-m-d'

Custom Casting

You can use functions with the names like get[CamelcaseAttributeName]Attribute() in order to cast your attributes to given format.

public function getMyattributeAttribute()
    return number_format($this->attributes['myattribute']);

Date casting

You can use inside your Eloquent the protected $dates array to type in your attributes that should be cast to dates.

This will automatically cast them as Carbon date object. However in order to have a fixed format to that date in cases you're working with outdated code like the one I am handling right one using Laravel forms you can overwrite the attribute given inside the Controller

$price_cut->myattribute = $price_cut->myattribute
    ? Carbon::createFromFormat('Y-m-d H:i:s', $price_cut->myattribute)->format('Y-m-d')
    : null;

NB: createFromFormat is significantly faster than using parse to guess the date format.

Casting dates and overwriting their format in cases

There is also the case where we use the raw date casting, but there is an instance where we need a different format and need to overwrite the Eloquent attributes itself

// Get the attributes in arrary..
$attributes = $MyModel->getAttributes();

// Overwrite the date format
$attributes['date_attribute'] = $attributes['date_attribute']
    ? Carbon::createFromFormat('Y-m-d H:i:s', $attributes['date_attribute'])->format('Y-m-d')
    : null;

// Go back and set the new attributes
$MyModel->setRawAttributes($attributes, true);

// Read bellow..

However in order for that to work we still need to remove the date casts predefined in our model. If we don't do that attributesToArray method in the HasAttributes trait will still return the Carbon object we don't need.

Doing that is quite easy. Create a method and execute it after setting the raw attributes.

    public function removeDates()
        $this->dates = [];

Now when we return $myModel->toArray() all dates are in the format required.