Skip to content

Instantly share code, notes, and snippets.

@jeremyworboys
Last active December 22, 2015 21:19
Show Gist options
  • Save jeremyworboys/6532802 to your computer and use it in GitHub Desktop.
Save jeremyworboys/6532802 to your computer and use it in GitHub Desktop.
<?php
trait DefaultsModel {
/**
* Default values to seed the model with
* @var Array
*/
protected $defaults = array();
/**
* Pre-fill default values in the model
*/
public function fillDefaults(array $attributes = array())
{
// Check if `defaults` is a method or property
// If it is a method, execute it otherwise just grab the value
$defaults = (method_exists($this, 'defaults')) ? $this->defaults() : $this->defaults;
// Merge defaults values
$attributes = array_merge($defaults, $attributes);
// Pass the merged attributes up the hierarchy
parent::__construct($attributes);
}
}
<?php
class Entry extends Eloquent {
use DefaultsModel;
public function __construct(array $attributes = array())
{
$this->fillDefaults($attributes);
}
/**
* The database table used by the model.
* @var String
*/
protected $table = 'entries';
/**
* Get the default attribute values
* @return Array
*/
protected function defaults()
{
return array(
'pubdate' => \Carbon\Carbon::now()
);
}
/**
* Get Date type fields
* @return Array
*/
public function getDates()
{
// Add `pubdate` to the list of Carbon date attributes
return array_merge(
parent::getDates(),
array(
'pubdate'
)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment