Skip to content

The behavior of the RequiredRuleInferrer is confusing #681

Open
@alexrififi

Description

@alexrififi

✏️ Describe the bug
If you make a property of a Data of type bool, then the Required auto rule will not be applied to it.

↪️ To Reproduce

use Illuminate\Validation\ValidationException;
use Spatie\LaravelData\Attributes\Validation\Required;
use Spatie\LaravelData\Data;
use Spatie\LaravelData\Exceptions\CannotCreateData;

it('successfully validated', function () {
    class SomeData1 extends Data
    {
        public function __construct(
            public string $just_string,
            public bool $i_am_bool,
        ) {
        }
    }

    $payload = ['just_string' => fake()->text()];
    $validated = SomeData1::validate($payload);
    expect($validated['just_string'])->toEqual($payload['just_string']);
});

it('validated, but not created', function () {
    class SomeData2 extends Data
    {
        public function __construct(
            public string $just_string,
            public bool $i_am_bool,
        ) {
        }
    }

    SomeData2::validateAndCreate(['just_string' => fake()->text()]);
})->throws(CannotCreateData::class);

it('fail validation', function () {
    class SomeData3 extends Data
    {
        public function __construct(
            public string $just_string,
            #[Required]
            public bool $i_am_bool,
        ) {
        }
    }

    SomeData3::validateAndCreate(['just_string' => fake()->text()]);
})->throws(ValidationException::class);

✅ Expected behavior

I expect that I won't have to manually add the Required attribute

🖥️ Versions

Laravel: 10.46.0
Laravel Data: 4.2.0
PHP: 8.3.1


The problem is here

if ($rules->hasType(BooleanType::class)) {
return false;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions