Casts and Mutators

Defining and Accessor

Laravel 9.x

use Illuminate\Database\Eloquent\Casts\Attribute;

protected function name(): Attribute
{
    return Attribute::make(
        get: fn (string $value) => strToUpper($value)
    );
}

This is a contrived example, but it shows how you can manipulate the value of the attribute.

protected function name(): Attribute
{
    return Attribute::make(
        get: fn () => 'Fish'
    );
}

Laravel 8.x

protected function getNameAttribute($value){
    return strToUpper($value);
}

Usage Examples

Return boolean if 'date' is set

protected function activatedAt(): Attribute
{
    return Attribute::make(
        get: fn ($value) => $value ? true : false,
    );
}
public function isMember(): bool
{
    return $this->activated_at !== null;
}

How to casts a data to a boolean, and save as date if true or null if false?

protected function activatedAt(): Attribute
{
    return Attribute::make(
        get: fn ($value) => $value ? true : false,
        set: fn ($value) => $value ? now() : null,
    );
}

The may be occasions where you want to display the actual date stored in the database, for this you can use the getOriginal() method.

public function getOriginalActivatedAt(){
    return $this->getOriginal('activated_at');
}

Trouble Shooting

Not mutating as expected

Make sure you have set the method name correctly in pascal case. For example, if you have an attribute published_at then the method name should be publishedAt().