Skip to content

Conversation

@u12206050
Copy link
Contributor

Currently when casting an attribute to asCollection it only casts it if the value isn't null, creating an issue when you want to start pushing or using the collection.

This PR ensures you always get a Collection but still maintains the null value in the database if the attribute is still empty and the original value was null upon saving.

Benefit: You can just use the attribute as a collection without checking if it is indeed a Collection

Maintains `null` value in database if the value is still empty and the original value was `null`

When casting attribute to `asCollection` you can now start using it without checking if it is set or not.
Allow setting the attribute to an empty array or even resetting back to null
@GrahamCampbell GrahamCampbell changed the title Ensure attribute is Collection when casting even if value is null p8.x] Ensure attribute is Collection when casting even if value is null Mar 24, 2021
@GrahamCampbell GrahamCampbell changed the title p8.x] Ensure attribute is Collection when casting even if value is null [8.x] Ensure attribute is Collection when casting even if value is null Mar 24, 2021
@GrahamCampbell
Copy link
Collaborator

Please add some tests.

@vdauchy
Copy link
Contributor

vdauchy commented Mar 24, 2021

Not sure how your code will interact with a nullable json column.
What I do to avoid your issue is to ensure your attribute is initialized, you can do that with the property:

YourModel extends Model {
    protected $attributes = [
        'you_collection_field' => '{}',
    ];
}

@u12206050
Copy link
Contributor Author

Not sure how your code will interact with a nullable json column.
What I do to avoid your issue is to ensure your attribute is initialized, you can do that with the property:

YourModel extends Model {
    protected $attributes = [
        'you_collection_field' => '{}',
    ];
}

It will still work with nullable columns. You will still be able to set the attribute to null or just save an empty Collection.
The only issue might be if you wanted to explicitly check if it is null, then you would need to do it on the getRawOriginal($key)

@taylorotwell
Copy link
Member

Seems like a breaking change. I don't really plan to change this behavior. Free to make your own cast if you need something different.

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.

5 participants