laravel-enum icon indicating copy to clipboard operation
laravel-enum copied to clipboard

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

Open tancou opened this issue 2 years ago • 2 comments

@spawnia Hi,

I want to talk about this change https://github.com/BenSampo/laravel-enum/commit/5094099a9ab9b710f6c262402598501886432699#diff-ee71af26064ea012953831df497c2297ea91606aa26bb133e73dc1b51deec2ccR603

which was discussed here https://github.com/BenSampo/laravel-enum/issues/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.

tancou avatar Mar 17 '22 14:03 tancou

I stand by https://github.com/BenSampo/laravel-enum/issues/244#issuecomment-1036307370

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

spawnia avatar Mar 17 '22 15:03 spawnia

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();
    }
}

tancou avatar Mar 17 '22 19:03 tancou

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

elev8studio avatar Nov 29 '22 18:11 elev8studio

Closing, as I no longer plan to develop this library further - see https://github.com/BenSampo/laravel-enum/issues/332.

spawnia avatar Feb 14 '24 14:02 spawnia