In the same way that we can use a boot{Trait}()
method in a trait/concern for an eloquent model, it would be nice to be able to register specific date fields in a trait/concern (i.e. Publishable
with a published_at
timestamp column).
trait Publishable
{
public function getPublishableDates()
{
return ['published_at'];
}
//
}
Here is the trait that will enable this functionality on your eloquent models.
trait HasTraitsWithDates
{
/**
* Get the attributes that should be converted to dates.
*
* @return array
*/
public function getDates()
{
$class = static::class;
foreach (class_uses_recursive($class) as $trait) {
$method = 'get'.class_basename($trait).'Dates');
if (method_exists($class, $method) {
$this->dates = array_unique(
array_merge($this->dates, $this->{$method}())
);
}
}
return parent::getDates();
}
}
The beautiful part is that this feature is additive in nature. Both default fields, created_at
and updated_at
, as well as those defined in the $dates
property on a model are still included with any trait based date fields when getDates()
is called.