For more information see DefaultModel Trait in Laravel 4.
Last active
December 22, 2015 21:19
-
-
Save jeremyworboys/6532802 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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