Skip to content

Instantly share code, notes, and snippets.

@olssonm
Created February 11, 2016 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olssonm/70373b699890100f5d31 to your computer and use it in GitHub Desktop.
Save olssonm/70373b699890100f5d31 to your computer and use it in GitHub Desktop.
Simple all-fetching method for a base model in Laravel 5+
/**
* 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