vincent15000's avatar

Difference between getLogoAttribute() and function logo(): Attribute

Hello,

I wonder what's the difference between both codes below.

protected function logo(): Attribute
{
    return new Attribute(
        get: fn () => $this->images->first()?->toUrl() ?? null,
    );
}

and

public function getLogoAttribute()
{
	return $this->images->first()?->toUrl() ?? null;
}

Thanks for your answer.

V

0 likes
3 replies
jayandholariya's avatar
Level 4

@vincent15000

The main difference between the two lies in Laravel version support and syntax style:

✅ getLogoAttribute() is the traditional accessor method, commonly used in Laravel 8 and earlier (though it still works in newer versions). It follows the get{StudlyCaseName}Attribute naming convention to define computed attributes.

✅ logo(): Attribute is the modern accessor syntax introduced in Laravel 9. It uses the Attribute class and allows you to define both a getter (get:) and setter (set:) in a clean, fluent way — all in one method.

1 like
kevinbui's avatar

I think the new way will shine when we have little logics around casting. The old way is still super valuable when we have lots of logics around generating a custom attribute.

For example, I have the following two custom attributes:

class Customer extends Model
{
    public function getVerifiedAttribute(): bool
    {
        if ($this->verified_by_partner)
        {
            return true;
        }

        return $this->documents()
            ->whereIn('type', ['driver_license', 'passport', 'national_id_card'])
            ->whereNotNull('verified_at')
            ->exists();
    }
    
    public function getFullNameAttribute(): string
    {
        return collect($this->only('first_name', 'middle_name', 'last_name'))
            ->filter()
            ->implode(' ');
    }   
}

The above logics looks totally fine as is, but will look gross wrapping around closures of the new way.

Please or to participate in this conversation.