Home > Article > Backend Development > How to Retrieve Custom Attributes in Laravel Models on Object Load?
Retrieve Custom Attributes in Laravel Models on Object Load
Problem:
You wish to access custom attributes/properties on a Laravel/Eloquent model upon model loading, without relying on manual loops.
Solution:
Laravel 8 :
Define your custom attribute as an Attribute with a getter function:
<code class="php">class EventSession extends Eloquent { public function availability() { return new Attribute( get: fn() => $this->calculateAvailability() ); } }</code>
Laravel 8-:
Method 1: Append your custom attribute to the $appends array and create a corresponding accessor:
<code class="php">class EventSession extends Eloquent { protected $appends = ['availability']; public function getAvailabilityAttribute() { return $this->calculateAvailability(); } }</code>
Method 2: Override the toArray() method to explicitly include your attribute:
<code class="php">class Book extends Eloquent { public function toArray() { $array = parent::toArray(); $array['upper'] = $this->upper; return $array; } public function getUpperAttribute() { return strtoupper($this->title); } }</code>
Method 3: Iterate through mutated attributes in toArray():
<code class="php">class Book extends Eloquent { public function toArray() { $array = parent::toArray(); foreach ($this->getMutatedAttributes() as $key) { if (!array_key_exists($key, $array)) { $array[$key] = $this->{$key}; } } return $array; } public function getUpperAttribute() { return strtoupper($this->title); } }</code>
The above is the detailed content of How to Retrieve Custom Attributes in Laravel Models on Object Load?. For more information, please follow other related articles on the PHP Chinese website!