Laravel's Eloquent ORM enhances accessor functionality with built-in caching and value object support. These features enable efficient handling of complex computations and structured data while maintaining clean, maintainable code.
This approach proves particularly valuable when working with computationally expensive operations or when you need to represent complex data structures as proper objects rather than plain arrays.
protected function complexStats(): Attribute{ return Attribute::make( get: fn () => $this->calculateStats() )->shouldCache();}
Here's an example implementing location handling with value objects:
<?php namespace App\Models; use App\ValueObjects\Location;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Casts\Attribute; class Store extends Model{ protected function location(): Attribute { return Attribute::make( get: fn ($value) => new Location( latitude: $this->latitude, longitude: $this->longitude, address: $this->address, timezone: $this->timezone ), set: function (Location $location) { return [ 'latitude' => $location->latitude, 'longitude' => $location->longitude, 'address' => $location->address, 'timezone' => $location->timezone ]; } )->shouldCache(); } protected function operatingHours(): Attribute { return Attribute::make( get: fn () => $this->calculateHours() )->withoutObjectCaching(); } private function calculateHours() { // Dynamic calculation based on timezone and current time return $this->location->getLocalHours(); }}
$store = Store::find(1);$store->location->address = '123 New Street';$store->save(); // Access operating hours (recalculated each time)$hours = $store->operatingHours;
Laravel's accessor features provide powerful tools for handling complex data structures and optimizing performance through intelligent caching.
