0

I'm using Spatie Laravel-data to create data objects to pass in and out of an API. I'm hitting an issue trying to create a DTO from a POST request - there are certain fields that won't be passed in for an INSERT, the obvious one being ID.

I'm failing validation each time, with the following error

{
"message": "The given data was invalid.",
"errors": {
    "id": [
        "The id field is required."
        ]
    }
}

My DTO class follows these instructions and looks like this:

class MemberData extends Data
{
    public function __construct(
        public int|Optional      $id,
        #[Max(255)]
        public string            $first_name,
        #[Max(255)]
        public string            $last_name,
    )
    {}
}

How can I get past validation without providing an ID? Or should I be creating a different DTO for an INSERT?

charliefortune
  • 3,072
  • 5
  • 28
  • 48

1 Answers1

2

Problem solved. If I had listened to the complaints from my IDE, I would have realised that Optional is a class that needs to be included.

Same goes for the attribute validation (Max)

Adding this to the top of the data object fixed the issue.

use Spatie\LaravelData\Optional;
use Spatie\LaravelData\Attributes\Validation\Max;
charliefortune
  • 3,072
  • 5
  • 28
  • 48