title: Laravel: Get Object From Collection By Attribute
body: <p>In Laravel, if I perform a query:</p>
  
  <pre><code>$foods = Food::where(...)-&gt;get();
  </code></pre>
  
  <p>...then <code>$foods</code> is an <a href="http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html" rel="noreferrer">Illuminate Collection</a> of <code>Food</code> model objects.  (Essentially an array of models.)</p>
  
  <p>However, the keys of this array are simply:</p>
  
  <pre><code>[0, 1, 2, 3, ...]
  </code></pre>
  
  <p>...so if I want to alter, say, the <code>Food</code> object with an <code>id</code> of 24, I can't do this:</p>
  
  <pre><code>$desired_object = $foods-&gt;get(24);
  $desired_object-&gt;color = 'Green';
  $desired_object-&gt;save();
  </code></pre>
  
  <p>...because this will merely alter the 25th element in the array, not the element with an <code>id</code> of 24.</p>
  
  <p><strong>How do I get a single (or multiple) element(s) from a collection by ANY attribute/column (such as, but not limited to, id / color / age / etc.)?</strong></p>
  
  <p>Of course, I can do this:</p>
  
  <pre><code>foreach ($foods as $food) {
      if ($food-&gt;id == 24) {
          $desired_object = $food;
          break;
      }
  }
  $desired_object-&gt;color = 'Green';
  $desired_object-&gt;save();
  </code></pre>
  
  <p>...but, that's just gross.</p>
  
  <p>And, of course, I can do this:</p>
  
  <pre><code>$desired_object = Food::find(24);
  $desired_object-&gt;color = 'Green';
  $desired_object-&gt;save();
  </code></pre>
  
  <p>...but that's <em>even more gross</em>, because it performs an additional unnecessary query when I already have the desired object in the <code>$foods</code> collection.</p>
  
  <p>Thanks in advance for any guidance.</p>
  
  <p>EDIT:</p>
  
  <p>To be clear, you <em>can</em> call <code>-&gt;find()</code> on an Illuminate Collection without spawning another query, but it <em>only</em> accepts a primary ID.  For instance:</p>
  
  <pre><code>$foods = Food::all();
  $desired_food = $foods-&gt;find(21);  // Grab the food with an ID of 21
  </code></pre>
  
  <p>However, there is still no clean (non-looping, non-querying) way to grab an element(s) by an attribute from a Collection, like this:</p>
  
  <pre><code>$foods = Food::all();
  $green_foods = $foods-&gt;where('color', 'green'); // This won't work.  :(
  </code></pre>