The error message suggests that the $expense_date argument in the ExpenseData constructor should be of type App\Data\Carbon, but a string is being passed instead.
To fix this issue, you need to make sure that the $expense_date argument is an instance of the Carbon class.
Here's how you can modify your code to resolve the error:
use Carbon\Carbon;
use Spatie\LaravelData\Data;
use Spatie\LaravelData\WithCast;
use Spatie\LaravelData\Casts\DateTimeInterfaceCast;
class ExpenseData extends Data
{
public function __construct(
public string|Optional $invoice_id,
#[WithCast(DateTimeInterfaceCast::class)]
public Carbon|string $expense_date,
public string $description,
public string $vendor,
public string|Optional $vat_number,
public int $gross_amount,
public int $vat_amount,
public int $net_amount,
public string|Optional $currency,
public string|Optional $note,
) {
if (is_string($expense_date)) {
$expense_date = Carbon::parse($expense_date);
}
$this->expense_date = $expense_date;
}
}
In the modified code, we added a type hint Carbon|string to the $expense_date property to indicate that it can accept either a Carbon instance or a string. Inside the constructor, we check if the provided value is a string, and if so, we parse it into a Carbon instance using Carbon::parse(). Finally, we assign the parsed Carbon instance back to the $expense_date property.
This should resolve the error and allow you to use the Spatie Laravel Data package to cast the date correctly.