PHP

Creating Custom Attribute Casts in Eloquent

Transform Eloquent model attributes to and from custom PHP objects or specific formats using advanced custom casting logic for complex data types.

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Arr;

class AddressCast implements CastsAttributes
{
    public function get($model, string $key, $value, array $attributes)
    {
        $decoded = json_decode($value, true);
        return new class($decoded) {
            public $street;
            public $city;
            public $zip;

            public function __construct(array $data)
            {
                $this->street = Arr::get($data, 'street');
                $this->city = Arr::get($data, 'city');
                $this->zip = Arr::get($data, 'zip');
            }

            public function fullAddress(): string
            {
                return $this->street . ', ' . $this->city . ' ' . $this->zip;
            }
        };
    }

    public function set($model, string $key, $value, array $attributes)
    {
        // $value could be an object, array or string
        if (is_object($value) && method_exists($value, 'toArray')) {
            return json_encode($value->toArray());
        } elseif (is_array($value)) {
            return json_encode($value);
        }
        return $value; // Assume it's already JSON string or null
    }
}

/* App\Models\User.php */
class User extends Model
{
    protected $casts = [
        'address' => AddressCast::class,
    ];
}

// Usage
$user = User::find(1);
echo $user->address->fullAddress();

$user->address = [
    'street' => '123 Main St',
    'city' => 'Anytown',
    'zip' => '12345'
];
$user->save();
How it works: Custom casts provide a powerful way to define how an Eloquent attribute is stored in the database and how it's retrieved. Here, `AddressCast` converts a JSON string from the database into an anonymous object with `street`, `city`, and `zip` properties (and a `fullAddress` method) upon retrieval. When setting the attribute, it converts an array or an object back into a JSON string. This allows you to work with complex data types as native PHP objects within your models.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs