0

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!

4
  • 1
    why do you need to turn it into a collection to just turn it back into an array? also that map call isn't actually doing anything Commented Jan 15, 2021 at 16:03
  • Why would you convert it to a Collection just to convert it back to an array... In fact, you shouldn't need to use ->toArray() at all; a Collection is perfectly fine, and will be converted to JSON from your backend (for example, or remain as a Collection, both of which are fine) Commented Jan 15, 2021 at 16:03
  • That is just debugging tool and I like how $var->toArray()) works for collection of models. I need array of models work in the same way Commented Jan 15, 2021 at 16:07
  • $permissions = Permission::orderBy('name', 'asc')->get(); is already a collection. Commented Jan 15, 2021 at 16:21

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.