-
Hi <?php
class AlbumData extends Data
{
public function __construct(
public Lazy|Label $label,
#[DataCollectionOf(SongData::class)]
public Lazy|DataCollection $songs,
) {
}
public static function fromRequest(Request $request): self
{
return new self(
label: Lazy::create(
fn() => LabelData::from(Label::findOrNew($request->label_id))
),
songs: Lazy::create(
fn() => SongData::collection(Song::whereIn('id', $request->collect('song_ids'))->get())
),
);
}
public static function fromModel(Album $album): self
{
return new self(
label: $album->label,
songs: SongData::collection($album->songs)
);
}
} So, as you can see, if data is loaded from request, than all properties are lazy. And if data loaded from model, all properties are not lazy. Let's say, I want to get properties ids somewhere in the code. If I do: $albumData->label->id;
$albumData->songs->toCollection()->pluck('id'); I will get the errors in case data was created from request:
But if I do: $albumData->label->resolve()->id;
$albumData->songs->resolve()->toCollection()->pluck('id'); I will get the errors in case data was created from model:
Is there any way provided by this package to get property of union type (Lazy type plus custom or primitive type)? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Such thing is not possible in PHP, so the answer is sadly no |
Beta Was this translation helpful? Give feedback.
-
This is something we cannot technically implement. Only when we resolve the whole data structure when calling include but such a thing is a) a massive breaking change b) something I don't now how it exactly would work, since you can call include multiple times and we don't want to have a performance hit from resolving c) even if we can resolve the complete structure, these includes are always manually defined so it is always possible a property is still Lazy. So you should always manually check if something is Lazy or not.
I don't think this should be added to the docs, since you're defining a union type, you as the PHP developer should know the value can be different types and you should check them all. |
Beta Was this translation helpful? Give feedback.
@rubenvanassche I created PR #403 with the fix of this issue. It turned out to be easier than I thought.