Search code examples
laravellaravel-collection

Can I convert array of models into collection of models?


In Laravel 8 Backend app with output

$var->toArray())

if $var is collection of models, then array of model values is outputted

But if $var - is array, which generated as :

$permissions          = Permission
    ::orderBy('name', 'asc')
    ->get()
    ->map(function ($permissionItem) use ($userPermissions) {
        return $permissionItem;
    })
    ->all();

$permissions - would be array of models. Can I to convert it into collection and use toArray() to it ?

Thanks!


Solution

  • Don't call all on your Collection. Calling all gives you the array of items. Just don't call all if you want to keep it as a Collection.

    If you are not in control of that call then you would need to make a Collection from your array and then do what you want with it:

    collect($var)->toArray()