0

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?

7
  • I'm not super-familiar with Laravel, but are you manually invoking the constructor, or is the framework. If it is you, I think you need to pass Optional::create() in order to make PHP happy. Commented Jul 1, 2024 at 18:35
  • I'm not sure where you got the string|Optional syntax from, but technically, you still need two arguments. I'd use string? $user_id = null in the declaration. Commented Jul 1, 2024 at 18:47
  • @UlrichEckhardt spatie.be/docs/laravel-data/v4/as-a-data-transfer-object/… it is in official documentation Commented Jul 1, 2024 at 18:49
  • Interesting. In any case, just arguing from the pure PHP side, your ctor takes two arguments. In the code where you try to create an instance, it does not provide a second parameter, which is why PHP at that point signals an error. Commented Jul 1, 2024 at 18:58
  • 2
    public string|Optional $user_id = new Optional() ? Also, what version of LaravelData you're using? Commented Jul 1, 2024 at 19:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.