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

enum arrayable casting #40693

Closed
makroxyz opened this issue Jan 28, 2022 · 1 comment
Closed

enum arrayable casting #40693

makroxyz opened this issue Jan 28, 2022 · 1 comment

Comments

@makroxyz
Copy link

  • Laravel Version: 8.81.0
  • PHP Version: 8.1.1

Description:

Different behaviour when casting to array an Enum implementing Arrayable class from collection and from eloquent model attribute.

Steps To Reproduce:

I have this enum

enum Status: string implements Arrayable
{
    case pending = 'pending';
    case done = 'done';
    
    /**
     * @inheritDoc
     */
    public function toArray()
    {
        return [
            'name' => $this->name,
            'value' => $this->value,
            'description' => "description of {$this->name}",
        ];
    }
}

In collection:

collect(Status::pending)->toArray();
/**
[
     "name" => "pending",
     "value" => "pending",
     "description" => "description of pending",
   ]
*/

in Model:

class MyModel extends Model
{
    protected $casts = [
        'status' => Status::class
    ];
}


MyModel::first()->toArray();
/**
[
    'id' => 1,
    'status' => 'pending'
]
*/

Even without Arrayable interface on enum the result is different.

Is it right?

How can I cast MyModel to array and have enum attribute (automatically) casted following the Arrayable interface?

This is related to a (closed) PR #40605. Should it be considered for 9.x?

@driesvints
Copy link
Member

Heya, this seems to be rejected. You can indeed always attempt a new PR for 9.x but it's up to Taylor in the end to accept or not.

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

No branches or pull requests

2 participants