Home > Article > Backend Development > How Can I Add Custom Attributes to Eloquent Models?
Adding Custom Attributes to Eloquent Models
The ability to augment Laravel/Eloquent models with custom attributes is essential for enhancing model representation. By default, models expose attributes corresponding to their table columns. However, accessing additional data or computations without querying the database is often desirable.
One challenge lies in populating custom attributes when models are loaded. The default toArray() method excludes accessors that do not map directly to table columns. To overcome this limitation:
Laravel versions >= 8:
Use the Attribute class with a getter function. This allows defining custom attributes with no direct relation to table columns.
<code class="php">class EventSession extends Eloquent { ... public function availability() { return new Attribute( get: fn () => $this->calculateAvailability() ); } ... }</code>
Laravel versions < 8:
Two options are available:
Option 1: Explicit Attribute Setting
Override the toArray() method and manually assign the custom 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); } ... }<p><strong>Option 2: Loop Through Custom Accessors</strong></p> <p>Iterate over all mutated attributes and apply them to the array representation.</p> <pre class="brush:php;toolbar:false"><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; } ... }</code>
By utilizing these techniques, developers can augment Eloquent models with custom attributes, enriching their representation and enhancing application functionality.
The above is the detailed content of How Can I Add Custom Attributes to Eloquent Models?. For more information, please follow other related articles on the PHP Chinese website!