From b71bd1470102efa3472c92ab13406cf88fec35fc Mon Sep 17 00:00:00 2001 From: Steve Bauman Date: Wed, 1 Dec 2021 08:40:21 -0500 Subject: [PATCH] Add ability to provide a default value when retrieving attributes --- src/Models/Concerns/HasAttributes.php | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/Models/Concerns/HasAttributes.php b/src/Models/Concerns/HasAttributes.php index 32bdf05f..b5f33357 100644 --- a/src/Models/Concerns/HasAttributes.php +++ b/src/Models/Concerns/HasAttributes.php @@ -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); @@ -274,7 +276,7 @@ public function getAttributeValue($key) return $this->castAttribute($key, $value); } - return $value; + return is_null($value) ? $default : $value; } /** @@ -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)), ); }