Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Garet's avatar
Level 3

In an Accessor what is the purpose of $attributes when you have access to $this ?

I'm using the "new" way of defining accessors and mutators (since Laravel 9) but there is one thing I am confused about. The documentation says: "Sometimes your accessor may need to transform multiple model attributes into a single "value object". To do so, your get closure may accept a second argument of $attributes, which will be automatically supplied to the closure and will contain an array of all of the model's current attributes"

So my accessor looks like this:

    protected function address(): Attribute
    {
        return Attribute::make(
            get: fn (mixed $value, array $attributes) => implode("\n", [
                $attributes['street'],
                $attributes['city'],
                $attributes['postcode']
            ]),
        );
    }

However, $this is available so it appears the same thing can be achieved like so:

    protected function address(): Attribute
    {
        return Attribute::make(
            get: fn () => implode("\n", [
                $this->street,
                $this->city,
                $this->postcode
            ]),
        );
    }

I'm confused under what circumstances you would ever need to use the second $attributes argument versus using $this ?

0 likes
3 replies
tykus's avatar

The $attributes array is the raw data from the database; whereas using the object property syntax will delegate to casts, accessors etc. It has always been documented that Accessors use the $attributes array, this is especially true whenever you use the Accessor to modify the original property.

1 like
Snapey's avatar

@tykus I'm still puzzled (also) since I always use $this->attributes['field'] and never knew about the passing attributes as a second parameter.

This was the original way I did accessors pre Laravel 9

Please or to participate in this conversation.