Collection of different data objects #254
Replies: 2 comments 1 reply
-
Hi @RichardGGD, This is not possible because it brings a lot of complications with it when we need to generate validation rules or magically create objects. If you really need such functionality, then I suggest using an array or Laravel Collection, but with this you'll lose some of the benefits the package provide. |
Beta Was this translation helpful? Give feedback.
-
Hi, I had this issue. I needed a collection of different types. Spatie's DTOs support it to a limited extent because they use collection classes. However, Laravel Data does not. So I created my own: https://gist.github.com/pixelated-au/ba061830592391219a66480baa09f739 You can use it like this: protected static function processFoo($ffItems): NonTypedCollection
{
return new NonTypedCollection(collect($ffItems)->map(fn($items) => FormFooResource::fromArray($items)));
} If using Spatie's TypeScript Transformer: public function __construct(
#[LiteralTypeScriptType("MyFooData[]")]
public NonTypedCollection $items,
){} Or like this: class MyFooDataCollection extends NonTypedCollection
{...} With TypeScript Transformer: #[LiteralTypeScriptType("MyFooData[]")]
class MyFooDataCollection extends NonTypedCollection
{...} I don't think it supports magic creation methods; it was a while ago that I created it and I can't fully remember. YMMV. But it's a small caveat for the benefit. Hope it helps! Oh and thanks @rubenvanassche and Spatie for your awesome contributions to open source! You guys are legends! |
Beta Was this translation helpful? Give feedback.
-
Is it possible to have a collection of different data objects?
For example, a PageLayout with a collection of different components.
But those components have different requirements so should have different Data Objects.
eg
Any suggestions for data like this?
Beta Was this translation helpful? Give feedback.
All reactions