Skip to content
This repository was archived by the owner on Jul 16, 2021. It is now read-only.

Casting a null value to a collection should return an empty collection #1278

Open
hackel opened this issue Aug 14, 2018 · 4 comments
Open

Casting a null value to a collection should return an empty collection #1278

hackel opened this issue Aug 14, 2018 · 4 comments

Comments

@hackel
Copy link

hackel commented Aug 14, 2018

When casting an Eloquent model attribute to a 'collection', if the value is currently null, the cast does not take place, and null is returned.

To avoid having to litter the code with existence tests for that attribute, and also be consistent with relationships, I propose an empty collection be returned instead.

On the saving side, there could also be logic to save an empty collection as null, but this is not critical.

Unfortunately this would be a breaking change. Any existence check e.g. if ($model->collection) would need to be changed to if ($model->collection->isEmpty()), but in many of those cases, I suspect the check would no longer be necessary.

@Miguel-Serejo
Copy link

null and empty collection can legitimately mean different things.

For example, a null value in the database can indicate that a user hasn't selected any preferences yet, while an empty collection can indicate that a user has specifically stated they have no preferences.

If in your app null and empty collection mean the same thing, I suggest making the default value of the column an empty collection rather than null.

@mfn
Copy link

mfn commented Aug 14, 2018

I'm with @36864 : null and empty collection can (and in many of my cases do) carry different semantics => 👎 on the idea.

@donnysim
Copy link

You can make a getter if you want an empty collection even if the value is null, would make more sense than breaking the behavior that is expected.

@andrey-helldar
Copy link

andrey-helldar commented Dec 27, 2019

@hackel, if I understand your problem correctly, the changes proposed in laravel/framework#30958 will make it easy to solve.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants