Skip to content

[8.x] Fix error when serializing resources with appended attributes#686

Merged
duncanmcclean merged 1 commit into8.xfrom
fix/resource-serialization
May 14, 2025
Merged

[8.x] Fix error when serializing resources with appended attributes#686
duncanmcclean merged 1 commit into8.xfrom
fix/resource-serialization

Conversation

@duncanmcclean
Copy link
Member

@duncanmcclean duncanmcclean commented May 14, 2025

This pull request fixes an error when attempting to serialize Runway's Resource object, which ultimately attempts to serialize a fresh instance of the Eloquent model.

However, since it serialises the fresh instance of the Eloquent model, no attributes are set, so model accessors using the $attributes parameter error out:

// app/Models/User.php

protected $appends = ['thingy'];

protected function thingy(): Attribute
{
    return Attribute::make(
        get: fn (mixed $value, array $attributes) => $attributes['name']
    );
}
use App\Models\User;

(new User)->toArray();
Undefined array key "name"

To prevent an error when serializing appended attributes on a fresh model, we're now simply returning the model's class name, rather than calling its toArray() method.

Fixes #685.

@duncanmcclean duncanmcclean marked this pull request as ready for review May 14, 2025 10:11
@duncanmcclean duncanmcclean merged commit 6e1b96e into 8.x May 14, 2025
37 checks passed
@duncanmcclean duncanmcclean deleted the fix/resource-serialization branch May 14, 2025 10:11
@github-actions
Copy link

Released as part of v8.4.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Can't use $attributes in model accessors and append them to the model

1 participant