title: In Laravel can you check to see if an object is in a Collection by using the object's primary key?
body: <p>I need a quick way to tell if an object is in a collection.  I'm building a template where an admin can assign a User a role.  The statement below is essentially what I'm trying to accomplish.</p>
  
  <p>IS the role with a primary key value of 5 in this collection of Roles.</p>
  
  <p><strong>What I'm doing (obviously dumbed down into one file):</strong></p>
  
  <pre><code>&lt;?php
  // The user
  $user = User::find(1);
  
  // Array of roles the user is associated with.  Fetched via a pivot table
  $tmpUserRoles = $user-&gt;roles-&gt;toArray();
  
  // Rebuilds the values from $tmpUserRoles so that the array key is the primary key
  $userRoles = array();
  foreach ($tmpUserRoles as $roleData) {
      $userRoles[$roleData['role_id']] = $roleData;
  }
  
  // This loop is used in the view.  Once again, this is dumbed down
  foreach ($Roles as $role) {
      if (isset($userRoles[$role-&gt;role_id]) {
          echo $user-&gt;firstName.' is a '.$role-&gt;label;
      } else {
          echo $user-&gt;firstName.' is not a '.$role-&gt;label;
      }
  }
  </code></pre>
  
  <p>Looping over an array just to create an identical array with the primary key as an index seems like a big waste of time.  Is there an easier way in Laravel to tell if an object is contained in a collection by using the object's primary key? </p>