Skip to content

Laravel attribute casting and accessors/mutators

PHP Dasun Kalupahana 70 views

<?php

use Illuminate\Database\Eloquent\Casts\Attribute;

protected function casts(): array
{
    return [
        'settings'     => 'array',
        'published_at' => 'datetime',
        'status'       => PostStatus::class, // backed enum
    ];
}

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

casts() converts columns to arrays, dates or enums automatically. Attribute::make transforms a value when you read or write it.

Learn more on the blog

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.