Below is my Data Transfer Object using Spatie\LaravelData\Data using Laravel Framework 9.52.16. In this definition $user_id is defined as optional property but yet when it is missing it throws an error.
<?php
namespace App\Http\DataTransferObjects\Listing;
use Spatie\LaravelData\Data;
use Spatie\LaravelData\Optional;
class ListingDTO extends Data
{
public function __construct(public string $type, public string|Optional $user_id)
{
}
}
Exception
"message": "App\\Http\\DataTransferObjects\\Listing\\ListingDTO::__construct(): Argument #2 ($user_id) not passed",
"exception": "ArgumentCountError",
....
How can I define optional properties?
Optional::create()in order to make PHP happy.string|Optionalsyntax from, but technically, you still need two arguments. I'd usestring? $user_id = nullin the declaration.public string|Optional $user_id = new Optional()? Also, what version of LaravelData you're using?