I'm using spatie/laravel-data module, but when I added a Lazy|Collection to my data class, trying to create from a model fails saying that the parameter is missing if the model doesn't pull in the relationship, but I don't see any difference between what I'm doing and what is described in the documentation. I assumed that Lazy would basically work like Optional in the scenario where I don't explicitly pull in the relationship.
Simplified for brevity, code looks something like this:
class FooData extends Data {
public function __construct(
public Optional|int $id,
public Optional|string $name,
public Lazy|Collection $bars,
// ...
) {}
public static function fromModel(Foo $foo): self
{
return new self(
id: $foo->id,
foo: $foo->name,
bars: Lazy::create(fn() => BarData::collect($foo->bars)),
// ...
);
}
}
class BarData extends Data {
public Optional|int $id,
public Optional|string $name,
}
class Foo extends Model {
// ...
public function bars() {
return $this->hasMany(Bar::class);
}
}
// All below fail with "the constructor requires n parameters, n-1 given."
FooData::from(Foo::first());
FooData::from(Foo::first())->include('bars');
FooData::from(Foo::with('bars')->first());
If I make the parameter Optional|Lazy|Collection $bars then it doesn't throw an error - but interestingly also DOES show a value for $foo->bars .
If I remove the Lazy part altogether (including the fromModel closure) - the value is also shown when loaded using Foo::with('bars') meaning it is fetched and passed to the underlying data object in some form (despite PHP's earlier protestations to the contrary).
What am I doing wrong? As far as I can tell I'm following the documentation as written here: https://spatie.be/docs/laravel-data/v4/as-a-resource/lazy-properties