Majeed's avatar

Convert a collection or object to an array

This is my query:

$data=Auth::user()->roles()->with('permissions')->get()->pluck('permissions');
 return $data;

The output of the query is as following:

     [
      [
       {
        id: 2,
        name: "Read",
        slug: "Read",
        description: "This is Simple Read Permission",
         pivot: {
         role_id: 2,
         permission_id: 2,
         },
        },
       {
        id: 3,
        name: "Update",
        slug: "Update",
        description: "This is Simple Update Permission",

        pivot: {
         role_id: 2,
         permission_id: 3,
        },
       },
      ]
     ]

**How can I convert this collection in to an array? **

0 likes
4 replies
MikeMacDowell's avatar
Level 25

@majeed

$data=Auth::user()->roles()->with('permissions')->get()->pluck('permissions')->flatten();

This will remove the "double" array, as you're getting a collection of roles and then plucking 'permissions' which returns an array itself.

1 like
Majeed's avatar

@MIKEMACDOWELL - @mikemacdowell thanks. it's working. but there is raise a duplicate value issue like:-

[
{
id: 1,
name: "Create",
slug: "Create",
description: "This is simple Create Permission",
created_at: "2018-12-17 18:54:07",
updated_at: "2018-12-17 18:54:07",
deleted_at: null,
pivot: {
role_id: 1,
permission_id: 1,
},
},

{
id: 3,
name: "Update",
slug: "Update",
description: "This is Simple Update Permission",
created_at: "2018-12-17 18:54:07",
updated_at: "2018-12-17 18:54:07",
deleted_at: null,
pivot: {
role_id: 1,
permission_id: 3,
},
},

{
id: 3,
name: "Update",
slug: "Update",
description: "This is Simple Update Permission",
created_at: "2018-12-17 18:54:07",
updated_at: "2018-12-17 18:54:07",
deleted_at: null,
pivot: {
role_id: 2,
permission_id: 3,
},
},
]

How can i made this unique...

MikeMacDowell's avatar

@majeed use unique on the collection

$data=Auth::user()->roles()->with('permissions')->get()->pluck('permissions')->flatten()->unique();

Please or to participate in this conversation.