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.
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 ?
Please or to participate in this conversation.