مقاله

casts()، AsEnumCollection، datetime، encrypted و mutator/accessor جدید — چطور داده را هنگام خواندن و نوشتن تمیز نگه داریم.

Cast و Mutator در Eloquent — تبدیل داده در Laravel 12

Cast و Mutator در Eloquent — تبدیل داده در Laravel 12

ستون published_at string است یا Carbon؟ فیلد meta JSON است یا array؟ بدون cast هر بار دستی decode می‌کنید و باگ timezone می‌گیرید. Cast و mutator در Eloquent مرز بین دیتابیس و domain model را مرتب می‌کند — در Laravel 11+ با متد casts() و کلاس Attribute.

تعریف cast در Laravel 12

protected function casts(): array
{
    return [
        'published_at' => 'datetime',
        'is_featured' => 'boolean',
        'meta' => 'array',
        'status' => PostStatus::class,
        'views' => 'integer',
    ];
}

PostStatus یک backed enum PHP 8.1+ است — PHP 8.3.

انواع cast پرکاربرد

  • datetime / immutable_datetime — Carbon
  • boolean — 0/1 به true/false
  • array / json — JSON column
  • encrypted — encrypt در DB
  • hashed — password یک‌طرفه
  • Enum::class — type-safe status

Accessor و Mutator مدرن

use Illuminate\Database\Eloquent\Casts\Attribute;

protected function title(): Attribute
{
    return Attribute::make(
        get: fn (string $value) => ucfirst($value),
        set: fn (string $value) => strtolower(trim($value)),
    );
}

یک attribute — get و set کنار هم. برای slug normalization مفید است.

Cast سفارشی

class MoneyCast implements CastsAttributes
{
    public function get($model, string $key, $value, array $attributes): float
    {
        return $value / 100;
    }

    public function set($model, string $key, $value, array $attributes): int
    {
        return (int) round($value * 100);
    }
}

قیمت به ریال در DB، تومان در app.

AsCollection و AsArrayObject

برای JSON پیچیده‌تر با متدهای collection.

mutator قدیمی vs Attribute

getXAttribute/setXAttribute هنوز کار می‌کند؛ Attribute روش توصیه‌شده Laravel جدید است.

append و hidden

protected $appends = ['excerpt_plain'];
protected $hidden = ['internal_notes'];

append accessor را در JSON اضافه می‌کند — مراقب N+1 در accessorهای سنگین باشید.

اشتباهات

  • cast datetime بدون timezone در APP_TIMEZONE
  • accessor با query سنگین (count relation)
  • ذخیره array بدون cast json
  • double encryption با cast encrypted + manual encrypt

جمع‌بندی

هر ستون non-scalar → cast. transform نمایشی → accessor. روابط، Observer برای side effect.

مدل‌سازی داده