og9t6w
Last Updated: February 25, 2016
·
15.31K
· searsaw

Rendering Dates as Carbon objects in Laravel

Working with dates in any language can be difficult. PHP is not any different. Though the DateTime class has tons of built in functionality, it still leaves some features to be desired. Thankfully, Brian Nesbitt has created the Carbon class. This is an extension to the basic PHP DateTime class.

Laravel uses this Carbon class in its framework. By default, the timestamps that are automatically added to any table you make are retrieved from the database as Carbon objects. However, what if you have another date column on there and you want it returned as a Carbon object as well.

After some digging, I found that the Eloquent base model has a method for controlling what dates are returned as Carbon objects. The method is below.

// vendor/laravel/framework/src/illuminate/Database/Eloquent/Model.php

/**
 * Get the attributes that should be converted to dates.
 *
 * @return array
 */
public function getDates()
{
    return array(static::CREATED_AT, static::UPDATED_AT, static::DELETED_AT);
}

This means that you can overwrite this method in your model classes and define which dates are returned as Carbon objects. If you just want to add a date column to this method, implement it something like the below code.

/**
 * Get the attributes that should be converted to dates.
 *
 * @return array
 */
public function getDates()
{
    return array_merge(parent::getDates(), array('purchase_date'));
}

Now whenever you retrieve the purchase_date from the database, you will be able to use the awesome methods that come from using the Carbon object. That was easy!

Update (September 26, 2013)

As of September 6, 2013, Taylor has merged some code into the Laravel framework that makes working with dates even easier! Instead of overriding the getDates() function, any extra date properties can now be added to a $dates array on the Eloquent model. These date properties will be automagically transformed into Carbon objects. Here is an example:</p>

class User extends Eloquent {

    protected $dates = array('purchase_date');

}

Now the purchase_date will be a Carbon object, which can then be manipulated easily!

1 Response
Add your response

14571

Thank you!

over 1 year ago ·