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

De-serialization exception #888

Open
kminek opened this issue Oct 16, 2024 · 1 comment
Open

De-serialization exception #888

kminek opened this issue Oct 16, 2024 · 1 comment

Comments

@kminek
Copy link

kminek commented Oct 16, 2024

✏️ Describe the bug
I am using version 4.10.1 and also i have validation_strategy set to always.

↪️ To Reproduce

class Event extends \Spatie\LaravelData\Data
{
    public function __construct(
        public string $name,
        public array $params = [],
    ) {}
}

class Post extends \Spatie\LaravelData\Data
{
    public function __construct(
        public string $title,
        /**
         * @var Collection<int, Event>
         */
        public Collection $history = new Collection,
    ) {}
}

$post = new Post(
    title: 'Lorem Ipsum',
);

$post->history->push(new Event(
    name: 'post.created',
));

$postArray = $post->toArray();

$postDeserialized = Post::from($postArray); // throws Exception
dump($postDeserialized);

I'm getting following exception:

 Illuminate\Validation\ValidationException  This field is required.

✅ Expected behavior
De-serialization should happen also when params are not set as the default value (empty array) is set in data object definition.

🖥️ Versions

Laravel: 11
Laravel Data: 4.10.1
PHP: 8.3

@rust17
Copy link
Contributor

rust17 commented Nov 7, 2024

It seems like the validation_strategy set to always is designed to validate all properties, including nested data.

Based on the documentation, the Event data appears to be nested within the history collection, which itself is nested within the Post object. This suggests that the validation rules for Event should be defined within a nested rules structure, similar to:

[
    'name' => ['required', 'string'],
    'params' => ['present', 'array', new NestedRules()],
]

However, in Laravel, the present rule requires the field to exist. If the params property is optional, you might consider making it nullable in your Event class:

        public function __construct(
            public string $name,
-            public array $params = [],
+            public ?array $params = [], 
        ) {}

This change would ensure that the validation rule for params is only applied when the field is actually present.

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