Casts

Casts

Eloquentity works seamlessly with Eloquent casts, but the Entity class must match the type that Eloquent casts to. Here's an example in Eloquent model:

app/Models/Customer.php
<?php
 
namespace App\Models;
 
use App\Support\Address;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
 
class Customer extends Model
{
    protected function address(): Attribute
    {
        return Attribute::make(
            get: fn (mixed $value, array $attributes) => new Address(
                $attributes['address_line_one'],
                $attributes['address_line_two']
            ),
            set: fn (Address $value) => [
                'address_line_one' => $value->lineOne,
                'address_line_two' => $value->lineTwo,
            ],
        );
    }
}

The corresponding Entity class using this cast should be defined as follows:

app/Entities/Customer.php
<?php
 
namespace App\Entities;
 
use App\Support\Address;
 
class Customer
{
    public function __construct(
        public readonly int $id,
        public readonly Address $address
    ) {}
}

This approach works with the casts method as well, supporting any cast type, including enums, dates, and so on. The key is to ensure that the type for the class property in the Entity class matches the type that Eloquent casts to.