spatie / laravel-data

Powerful data objects for Laravel
https://spatie.be/docs/laravel-data/
MIT License
1.29k stars 210 forks source link

RequiredWith not working as expected #853

Closed scippio closed 1 month ago

scippio commented 2 months ago

✏️ Describe the bug I think there is a bad behaviour with RequiredWith attribute.

↪️ To Reproduce¨


it('cannot validate MyData', function () {
    class MyData extends Data
    {
        public function __construct(
            public string $name,
            #[Unique(User::class, 'email')]
            public string $email,
            #[RequiredWith('street')]
            public string|Optional $city,
            #[RequiredWith('city')]
            public string|Optional $street
        ) {
        }
    }

    // Validation exception is not thrown (off course it is but for documentation purposes it is not)
    dd(MyData::validateAndCreate([
           'name' => 'Ruben',
           'email' => 'test@example.com',
           'street' => 'MyStreet'
     ]));
});

✅ Expected behavior I think there should be validate error like: "The city field is required when street is present.", but the request is accepted. The "rules" function with "required_with" works as expected.

    public static function rules(): array
    {
        return [
            'email' => ...,
            'city' => ['required_with:street'],
            'street' => ['required_with:city'],
        ];
    }

🖥️ Versions

Laravel: 11 Laravel Data: 4.6.0 PHP: 8.3.6

scippio commented 2 months ago

I think it's same as https://github.com/spatie/laravel-data/issues/844

bryanlopezinc commented 1 month ago

@scippio i feel the combination of the sometimes (in this case Optional) and required_with rules creates a conflict.

scippio commented 1 month ago

Yes.

bryanlopezinc commented 1 month ago

@scippio What I meant to say is your data class validation doesn't work because of the Optional type for both properties which translates to "sometimes". notice how the rules method work.

scippio commented 1 month ago

So it's a laravel-data bug? Because Laravel works as expected.

rubenvanassche commented 1 month ago

Duplicate indeed, fixed in next release!