Skip to content

[9.x] Fix default pivot attributes - #40947

Merged
taylorotwell merged 2 commits into
laravel:9.xfrom
iamgergo:9.x
Feb 12, 2022
Merged

[9.x] Fix default pivot attributes#40947
taylorotwell merged 2 commits into
laravel:9.xfrom
iamgergo:9.x

Conversation

@iamgergo

Copy link
Copy Markdown
Contributor

This PR attempts to fix an issue, when a custom pivot model is being used with default attributes. Related PR: #18127


Let's say I have the same pivot setup as the linked PR, but also, my pivot has default attributes:

class UserTeamPivot extends Pivot
{
    protected $attributes = ['permissions' => '["create_campaign"]'];

    protected $casts = ['permissions' => 'json'];
}

It works well, when just creating a new instance:

(new UserTeamPivot())->toArray(); // ['permissions' => ['create_campaign']]

But fails when creating a new pivot via the relation instance, it just simply overrides the default attributes that are defined in the pivot model's $attributes property:

$user->teams()->newPivot()->toArray(); // []

In my opinion, this is a bug, because if I want the default attributes to be empty, then I won't define them, but if they are defined, then they should be present in a fresh pivot instance.

Casting should be working as before, and I think this is not a BC.

@crynobone

Copy link
Copy Markdown
Member

This should definitely includes some tests

@iamgergo

Copy link
Copy Markdown
Contributor Author

I've added a test that covers the described issue. Let me know if something else should be added.

@taylorotwell
taylorotwell merged commit 6c5ecc1 into laravel:9.x Feb 12, 2022
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.

3 participants