17

I have two arrays, $user_roles and $global_roles. I want to make a new array, let's call it $available_roles, where it can be equated as the items in $global_roles less the items in the $user_roles

I have the following code to do it to a normal array. $available_roles = array_unique(array_merge($global_roles, $user_roles), SORT_REGULAR);

This is proving to be problematic due to the fact that Laravel does not use traditional arrays when one executes a query, it uses Eloquent Collections.

What other ideas do you guys have?

Rijnhardt
  • 2,344
  • 5
  • 19
  • 27

1 Answers1

31

This is fairly simple. You can use the Collection's merge method:

$available_roles = $global_roles->merge($user_roles);

Because merge internally uses an associative array (dictionary) that uses the id as key, this should automatically remove duplicates.

Anyways though, you can remove duplicates in a collection using unique:

$uniqueCollection = $collection->unique();

Now that was for merging what you're actually are looking for is the difference between two collections. You can do this in two ways:

$available_roles = $user_roles->diff($global_roles);

or

$available_roles = $global_roles->except($user_roles->modelKeys());
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • I understand how it is supposed to work, but it doesn't seem to be working the way that I intended it to. Here is a picture of what the Two Collections are looking like rendered. (http://i.imgur.com/JGIN5en.png) If my reasoning is correct, shouldn't the available roles be empty because the User already has the roles assigned to him – Rijnhardt Apr 04 '15 at 12:49
  • 1
    Ah I see. You are not trying to *merge* them at all. What you want is the difference between the two. Try `$available_roles = $user_roles->diff($global_roles);` or also `$available_roles = $global_roles->except($user_roles->modelKeys());` – lukasgeiter Apr 04 '15 at 13:11