Skip to content

Commit

Permalink
Add ability to provide a default value when retrieving attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
stevebauman committed Dec 1, 2021
1 parent a02348a commit b71bd14
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/Models/Concerns/HasAttributes.php
Expand Up @@ -238,26 +238,28 @@ public function fill(array $attributes = [])
* Returns the models attribute by its key.
*
* @param int|string $key
* @param mixed $default
*
* @return mixed
*/
public function getAttribute($key)
public function getAttribute($key, $default = null)
{
if (! $key) {
return;
}

return $this->getAttributeValue($key);
return $this->getAttributeValue($key, $default);
}

/**
* Get an attributes value.
*
* @param string $key
* @param mixed $default
*
* @return mixed
*/
public function getAttributeValue($key)
public function getAttributeValue($key, $default = null)
{
$key = $this->normalizeAttributeKey($key);
$value = $this->getAttributeFromArray($key);
Expand All @@ -274,7 +276,7 @@ public function getAttributeValue($key)
return $this->castAttribute($key, $value);
}

return $value;
return is_null($value) ? $default : $value;
}

/**
Expand Down Expand Up @@ -686,13 +688,14 @@ protected function getNormalizedAttributes()
* Returns the first attribute by the specified key.
*
* @param string $key
* @param mixed $default
*
* @return mixed
*/
public function getFirstAttribute($key)
public function getFirstAttribute($key, $default = null)
{
return Arr::first(
Arr::wrap($this->getAttribute($key))
Arr::wrap($this->getAttribute($key, $default)),
);
}

Expand Down

0 comments on commit b71bd14

Please sign in to comment.