Created
February 11, 2016 14:34
-
-
Save olssonm/70373b699890100f5d31 to your computer and use it in GitHub Desktop.
Simple all-fetching method for a base model in Laravel 5+
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
/** | |
* Retrieve an attribute value, or a default value, depending on if attribute is set | |
* @param string $attribute name of attribute | |
* @param mixed $default the default value | |
* @return mixed the attribute | |
*/ | |
public function attr($attribute, $default = null) | |
{ | |
if (isset($this->attributes[$attribute]) && $this->attributes[$attribute] != null) { | |
return $this->attributes[$attribute]; | |
} elseif (strpos($attribute, '.') !== false) { | |
// Allow "dot notation" for fetching values | |
list($table, $column) = explode('.', $attribute); | |
if($this->{$table}) { | |
if (isset($this->{$table}->{$column}) && $this->{$table}->{$column} != null) { | |
return $this->{$table}->{$column}; | |
} | |
} | |
} | |
return $default; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment