Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why jsonSerialize() does not return toArray() anymore? #257

Closed
tancou opened this issue Mar 17, 2022 · 4 comments
Closed

Why jsonSerialize() does not return toArray() anymore? #257

tancou opened this issue Mar 17, 2022 · 4 comments

Comments

@tancou
Copy link

tancou commented Mar 17, 2022

@spawnia Hi,

I want to talk about this change 5094099#diff-ee71af26064ea012953831df497c2297ea91606aa26bb133e73dc1b51deec2ccR603

which was discussed here #244

I think this change must be documented, at leat, as it breaks the behavior explained in the documentation of the "Customising $model->toArray() behavior" https://github.com/BenSampo/laravel-enum#customising-model-toarray-behaviour

Laravel for json responses uses jsonSerialize(), which previously used toArray() returned. Now both functions are independent, and for array AND json, we need to customize the return.

Personally, I think this makes more sense to revert to the behavior of jsonSerialize() which returns the toArray() function.

@spawnia
Copy link
Collaborator

spawnia commented Mar 17, 2022

I stand by #244 (comment)

I think we should remove the implementation of Arrayable completely instead.

@tancou
Copy link
Author

tancou commented Mar 17, 2022

In that case, is it still possible to cast the object into an array, a json or a string?
Is it better to use a custom implementation of the cast methods? Or create a config variable to define default action? Maybe define multiple traits to specify (globally or locally) how to cast Enum ?

That's for sure a breaking change for the next major version, but I think having changed jsonSerialize() is already a breaking change for everyone relying on a custom implementation of toArray().

For my particular case on a projet, in order to restaure my previous behaviour (return an array of the object), i've created the following trait :

<?php

namespace App\Enums;

trait BenSampoEnumArrayable
{
    public function toArray(): mixed
    {
        return $this;
    }

    public function jsonSerialize(): mixed
    {
        return $this->toArray();
    }
}

@elev8studio
Copy link

This just saved me from hours of banging my head against the wall. Thanks!

@spawnia
Copy link
Collaborator

spawnia commented Feb 14, 2024

Closing, as I no longer plan to develop this library further - see #332.

@spawnia spawnia closed this as not planned Won't fix, can't repro, duplicate, stale Feb 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants