Home > Article > Backend Development > How to Add Custom Attributes to Laravel/Eloquent Models on Load?
Custom Attributes in Laravel/Eloquent Models on Load
The challenge arises when attempting to add custom attributes to an Eloquent model when it is initially loaded. This prevents the need for manual attribute population using loops. While model events have been explored, they have not yielded desired results.
Solution
The underlying issue stems from the toArray() method disregarding accessors not directly corresponding to database table columns. However, Laravel provides a straightforward workaround:
Laravel >= 8.0
Introduce an Attribute class with a getter function to calculate the custom attribute:
<code class="php">class EventSession extends Eloquent { public function availability() { return new Attribute(get: fn () => $this->calculateAvailability()); } }</code>
Laravel < 8.0 and >= 4.08
Add the custom attribute to the $appends property and define the getter accessor:
<code class="php">class EventSession extends Eloquent { protected $appends = ['availability']; public function getAvailabilityAttribute() { return $this->calculateAvailability(); } }</code>
Laravel < 4.08
Override the toArray() method to explicitly set the attribute or loop through mutated attributes to retrieve their values:
<code class="php">class EventSession extends Eloquent { public function toArray() { $array = parent::toArray(); $array['availability'] = $this->availability; return $array; } }<p>or</p> <pre class="brush:php;toolbar:false"><code class="php">class EventSession extends Eloquent { public function toArray() { $array = parent::toArray(); foreach ($this->getMutatedAttributes() as $key) { $array[$key] = $this->$key; } return $array; } }</code>
By implementing these solutions, custom attributes can be easily added to Eloquent models upon loading, eliminating the need for manual attribute population.
The above is the detailed content of How to Add Custom Attributes to Laravel/Eloquent Models on Load?. For more information, please follow other related articles on the PHP Chinese website!