rsarvarov's avatar

Elegant way to wrap model into collection?

I want to work with collections even if data is single model:

So if I do collect($collectionOfModels) its do nothing = GOOD.

If I do collect($singleModel) its wraps all model's properties (instead of model) like this:

array:2 [
  "id" => 1
  "name" => "Alex"
]

But I want this:

array:1 [
  array:2 ["id" => 1, "name" => "Alex"],
]

So every time I do that trick:

$collectionOrSingleModel = getData();

if ($collectionOrSingleModel instanceof Model) {
    $collectionOrSingleModel  = collect([collectionOrSingleModel ]);
}

foreach ($collectionOrSingleModel as $singleModel) {
    // ...
}


It works fine but I don't feel good. Is there any better way to do that?

0 likes
4 replies
martinbean's avatar

I want to work with collections even if data is single model

@rsarvarov That’s not what collections are for.

It might help if you told us what problem it is you’re trying to solve, and not how you‘re trying to solve it. But it seems collections is not the answer from your description and code sample.

Ishra's avatar
Ishra
Best Answer
Level 6

@rsarvarov maybe the wrap method is what you are looking for?

https://laravel.com/docs/8.x/collections#method-wrap

$collectionOfModels = Collection::wrap($singleModelOrCollectionOfModels);

@martinbean One reason could be to pass it into a function that expects a Collection of models i guess, then it makes sense to convert a single model to a Collection before using the function, not sure that is was rsarvarov is doing, but that is one usecase i can think of.

3 likes

Please or to participate in this conversation.