Laravel: Get Object From Collection By Attribute





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







59















In Laravel, if I perform a query:



$foods = Food::where(...)->get();


...then $foods is an Illuminate Collection of Food model objects. (Essentially an array of models.)



However, the keys of this array are simply:



[0, 1, 2, 3, ...]


...so if I want to alter, say, the Food object with an id of 24, I can't do this:



$desired_object = $foods->get(24);
$desired_object->color = 'Green';
$desired_object->save();


...because this will merely alter the 25th element in the array, not the element with an id of 24.



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.)?



Of course, I can do this:



foreach ($foods as $food) {
if ($food->id == 24) {
$desired_object = $food;
break;
}
}
$desired_object->color = 'Green';
$desired_object->save();


...but, that's just gross.



And, of course, I can do this:



$desired_object = Food::find(24);
$desired_object->color = 'Green';
$desired_object->save();


...but that's even more gross, because it performs an additional unnecessary query when I already have the desired object in the $foods collection.



Thanks in advance for any guidance.



EDIT:



To be clear, you can call ->find() on an Illuminate Collection without spawning another query, but it only accepts a primary ID. For instance:



$foods = Food::all();
$desired_food = $foods->find(21); // Grab the food with an ID of 21


However, there is still no clean (non-looping, non-querying) way to grab an element(s) by an attribute from a Collection, like this:



$foods = Food::all();
$green_foods = $foods->where('color', 'green'); // This won't work. :(









share|improve this question































    59















    In Laravel, if I perform a query:



    $foods = Food::where(...)->get();


    ...then $foods is an Illuminate Collection of Food model objects. (Essentially an array of models.)



    However, the keys of this array are simply:



    [0, 1, 2, 3, ...]


    ...so if I want to alter, say, the Food object with an id of 24, I can't do this:



    $desired_object = $foods->get(24);
    $desired_object->color = 'Green';
    $desired_object->save();


    ...because this will merely alter the 25th element in the array, not the element with an id of 24.



    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.)?



    Of course, I can do this:



    foreach ($foods as $food) {
    if ($food->id == 24) {
    $desired_object = $food;
    break;
    }
    }
    $desired_object->color = 'Green';
    $desired_object->save();


    ...but, that's just gross.



    And, of course, I can do this:



    $desired_object = Food::find(24);
    $desired_object->color = 'Green';
    $desired_object->save();


    ...but that's even more gross, because it performs an additional unnecessary query when I already have the desired object in the $foods collection.



    Thanks in advance for any guidance.



    EDIT:



    To be clear, you can call ->find() on an Illuminate Collection without spawning another query, but it only accepts a primary ID. For instance:



    $foods = Food::all();
    $desired_food = $foods->find(21); // Grab the food with an ID of 21


    However, there is still no clean (non-looping, non-querying) way to grab an element(s) by an attribute from a Collection, like this:



    $foods = Food::all();
    $green_foods = $foods->where('color', 'green'); // This won't work. :(









    share|improve this question



























      59












      59








      59


      13






      In Laravel, if I perform a query:



      $foods = Food::where(...)->get();


      ...then $foods is an Illuminate Collection of Food model objects. (Essentially an array of models.)



      However, the keys of this array are simply:



      [0, 1, 2, 3, ...]


      ...so if I want to alter, say, the Food object with an id of 24, I can't do this:



      $desired_object = $foods->get(24);
      $desired_object->color = 'Green';
      $desired_object->save();


      ...because this will merely alter the 25th element in the array, not the element with an id of 24.



      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.)?



      Of course, I can do this:



      foreach ($foods as $food) {
      if ($food->id == 24) {
      $desired_object = $food;
      break;
      }
      }
      $desired_object->color = 'Green';
      $desired_object->save();


      ...but, that's just gross.



      And, of course, I can do this:



      $desired_object = Food::find(24);
      $desired_object->color = 'Green';
      $desired_object->save();


      ...but that's even more gross, because it performs an additional unnecessary query when I already have the desired object in the $foods collection.



      Thanks in advance for any guidance.



      EDIT:



      To be clear, you can call ->find() on an Illuminate Collection without spawning another query, but it only accepts a primary ID. For instance:



      $foods = Food::all();
      $desired_food = $foods->find(21); // Grab the food with an ID of 21


      However, there is still no clean (non-looping, non-querying) way to grab an element(s) by an attribute from a Collection, like this:



      $foods = Food::all();
      $green_foods = $foods->where('color', 'green'); // This won't work. :(









      share|improve this question
















      In Laravel, if I perform a query:



      $foods = Food::where(...)->get();


      ...then $foods is an Illuminate Collection of Food model objects. (Essentially an array of models.)



      However, the keys of this array are simply:



      [0, 1, 2, 3, ...]


      ...so if I want to alter, say, the Food object with an id of 24, I can't do this:



      $desired_object = $foods->get(24);
      $desired_object->color = 'Green';
      $desired_object->save();


      ...because this will merely alter the 25th element in the array, not the element with an id of 24.



      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.)?



      Of course, I can do this:



      foreach ($foods as $food) {
      if ($food->id == 24) {
      $desired_object = $food;
      break;
      }
      }
      $desired_object->color = 'Green';
      $desired_object->save();


      ...but, that's just gross.



      And, of course, I can do this:



      $desired_object = Food::find(24);
      $desired_object->color = 'Green';
      $desired_object->save();


      ...but that's even more gross, because it performs an additional unnecessary query when I already have the desired object in the $foods collection.



      Thanks in advance for any guidance.



      EDIT:



      To be clear, you can call ->find() on an Illuminate Collection without spawning another query, but it only accepts a primary ID. For instance:



      $foods = Food::all();
      $desired_food = $foods->find(21); // Grab the food with an ID of 21


      However, there is still no clean (non-looping, non-querying) way to grab an element(s) by an attribute from a Collection, like this:



      $foods = Food::all();
      $green_foods = $foods->where('color', 'green'); // This won't work. :(






      php mysql laravel






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 9 '15 at 0:21







      Leng

















      asked Jan 5 '14 at 7:00









      LengLeng

      1,58511525




      1,58511525
























          9 Answers
          9






          active

          oldest

          votes


















          83














          You can use filter, like so:



          $desired_object = $food->filter(function($item) {
          return $item->id == 24;
          })->first();


          filter will also return a Collection, but since you know there will be only one, you can call first on that Collection.



          You don't need the filter anymore (or maybe ever, I don't know this is almost 4 years old). You can just use first:



          $desired_object = $food->first(function($item) {
          return $item->id == 24;
          });





          share|improve this answer





















          • 7





            Hey, thanks! I think I can live with that. Still unusually verbose in my opinion for what is usually such an 'Eloquent' framework haha. But it's still much cleaner than the alternatives so far, so I'll take it.

            – Leng
            Jan 5 '14 at 7:09













          • As @squaretastic is pointing out in the other answer, inside your closure you're making an assignement and not a comparison (i.e. you should == and not = )

            – St0rM
            Jun 9 '14 at 12:57






          • 22





            Actually it's not even necessary to call filter()->first() you can just call first(function(...))

            – lukasgeiter
            Feb 4 '15 at 20:10











          • from Laravel Collection documentation. laravel.com/docs/5.5/collections#method-first collect([1, 2, 3, 4])->first(function ($value, $key) { return $value == 2; });

            – Shiro
            Dec 12 '17 at 15:25






          • 2





            You can do same thing with where function. $desired_object = $food->where('id', 24)->first();

            – Bhavin Thummar
            Aug 28 '18 at 11:02



















          86














          Laravel provides a method called keyBy which allows to set keys by given key in model.



          $collection = $collection->keyBy('id');



          will return the collection but with keys being the values of id attribute from any model.



          Then you can say:



          $desired_food = $foods->get(21); // Grab the food with an ID of 21



          and it will grab the correct item without the mess of using a filter function.






          share|improve this answer





















          • 2





            Really useful, especially for performance, ->first() can be slow when called multiple times (foreach in foreach...) so you can "index" your collection like : $exceptions->keyBy(function ($exception) { return $exception->category_id . ' ' . $exception->manufacturer_id; and use ->get($category->id . ' ' . $manufacturer->id) after !

            – François Breton
            Apr 25 '16 at 16:32













          • Does this key continue to be used when new items are added to the collection? Or do I need to use keyBy() every time a new object or array is pushed onto the collection?

            – Jason
            Sep 22 '16 at 14:22











          • Most likely you have to call it again since keyBy returns new collection from what I remember, not sure though, you can check Illuminate/Support/Collection to find it out. (Not working in Laravel for quite some time so someone can correct me).

            – Maksym Cierzniak
            Dec 4 '16 at 20:44











          • This didn't worked for me, it returned another item, the next item, if I type get(1) it will return the item which has number 2 as id.

            – Jaqueline Passos
            Jan 21 '17 at 16:42





















          7














          Since I don't need to loop entire collection, I think it is better to have helper function like this



          /**
          * Check if there is a item in a collection by given key and value
          * @param IlluminateSupportCollection $collection collection in which search is to be made
          * @param string $key name of key to be checked
          * @param string $value value of key to be checkied
          * @return boolean|object false if not found, object if it is found
          */
          function findInCollection(IlluminateSupportCollection $collection, $key, $value) {
          foreach ($collection as $item) {
          if (isset($item->$key) && $item->$key == $value) {
          return $item;
          }
          }
          return FALSE;
          }





          share|improve this answer































            5














            Use the built in collection methods contain and find, which will search by primary ids (instead of array keys). Example:



            if ($model->collection->contains($primaryId)) {
            var_dump($model->collection->find($primaryId);
            }


            contains() actually just calls find() and checks for null, so you could shorten it down to:



            if ($myModel = $model->collection->find($primaryId)) {
            var_dump($myModel);
            }





            share|improve this answer
























            • We understand that find() accepts a primary ID. What we want is a method that accepts any attribute, such as "color" or "age". So far, kalley's method is the only one that works for any attribute.

              – Leng
              Jan 13 '15 at 1:08



















            5














            I know this question was originally asked before Laravel 5.0 was released, but as of Laravel 5.0, Collections support the where() method for this purpose.



            For Laravel 5.0, 5.1, and 5.2, the where() method on the Collection will only do an equals comparison. Also, it does a strict equals comparison (===) by default. To do a loose comparison (==), you can either pass false as the third parameter or use the whereLoose() method.



            As of Laravel 5.3, the where() method was expanded to work more like the where() method for the query builder, which accepts an operator as the second parameter. Also like the query builder, the operator will default to an equals comparison if none is supplied. The default comparison was also switched from strict by default to loose by default. So, if you'd like a strict comparison, you can use whereStrict(), or just use === as the operator for where().



            Therefore, as of Laravel 5.0, the last code example in the question will work exactly as intended:



            $foods = Food::all();
            $green_foods = $foods->where('color', 'green'); // This will work. :)

            // This will only work in Laravel 5.3+
            $cheap_foods = $foods->where('price', '<', 5);

            // Assuming "quantity" is an integer...
            // This will not match any records in 5.0, 5.1, 5.2 due to the default strict comparison.
            // This will match records just fine in 5.3+ due to the default loose comparison.
            $dozen_foods = $foods->where('quantity', '12');





            share|improve this answer































              3














              I have to point out that there is a small but absolutely CRITICAL error in kalley's answer. I struggled with this for several hours before realizing:



              Inside the function, what you are returning is a comparison, and thus something like this would be more correct:



              $desired_object = $food->filter(function($item) {
              return ($item->id **==** 24);
              })->first();





              share|improve this answer



















              • 1





                Yes, thanks for pointing this out. It's also important to note that the filter function is no different from my foreach() example performance-wise, because it just does the same kind of loop... in fact, my foreach() example is better performing because it breaks upon finding the correct model. Also... {Collection}->find(24) will grab by primary key, which makes it the best option here. The filter Kalley proposed is actually identical to $desired_object = $foods->find(24);.

                – Leng
                May 16 '14 at 4:38








              • 1





                Never seen the **==** operator, what does it do?

                – kiradotee
                Jun 1 '17 at 12:42











              • @kiradotee I think the OP was just attempting to emphasize the double equal comparison operator (==). The original answer only used one equal sign, so it was doing an assignment instead of comparison. OP was trying to emphasize there should be two equal signs.

                – patricus
                Jun 3 '17 at 2:01





















              3














              As from Laravel 5.5 you can use firstWhere()



              In you case:



              $green_foods = $foods->firstWhere('color', 'green');





              share|improve this answer



















              • 1





                This should be the accepted answer after Laravel 5.5

                – beerwin
                Mar 13 at 16:13



















              1














              Elegant solution for finding a value (http://betamode.de/2013/10/17/laravel-4-eloquent-check-if-there-is-a-model-with-certain-key-value-pair-in-a-collection/) can be adapted:



              $desired_object_key = $food->array_search(24, $food->lists('id'));
              if ($desired_object_key !== false) {
              $desired_object = $food[$desired_object_key];
              }





              share|improve this answer































                0














                As the question above when you are using the where clause you also need to use the get Or first method to get the result.



                /**
                *Get all food
                *
                */

                $foods = Food::all();

                /**
                *Get green food
                *
                */

                $green_foods = Food::where('color', 'green')->get();





                share|improve this answer
























                  Your Answer






                  StackExchange.ifUsing("editor", function () {
                  StackExchange.using("externalEditor", function () {
                  StackExchange.using("snippets", function () {
                  StackExchange.snippets.init();
                  });
                  });
                  }, "code-snippets");

                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "1"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f20931020%2flaravel-get-object-from-collection-by-attribute%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  9 Answers
                  9






                  active

                  oldest

                  votes








                  9 Answers
                  9






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  83














                  You can use filter, like so:



                  $desired_object = $food->filter(function($item) {
                  return $item->id == 24;
                  })->first();


                  filter will also return a Collection, but since you know there will be only one, you can call first on that Collection.



                  You don't need the filter anymore (or maybe ever, I don't know this is almost 4 years old). You can just use first:



                  $desired_object = $food->first(function($item) {
                  return $item->id == 24;
                  });





                  share|improve this answer





















                  • 7





                    Hey, thanks! I think I can live with that. Still unusually verbose in my opinion for what is usually such an 'Eloquent' framework haha. But it's still much cleaner than the alternatives so far, so I'll take it.

                    – Leng
                    Jan 5 '14 at 7:09













                  • As @squaretastic is pointing out in the other answer, inside your closure you're making an assignement and not a comparison (i.e. you should == and not = )

                    – St0rM
                    Jun 9 '14 at 12:57






                  • 22





                    Actually it's not even necessary to call filter()->first() you can just call first(function(...))

                    – lukasgeiter
                    Feb 4 '15 at 20:10











                  • from Laravel Collection documentation. laravel.com/docs/5.5/collections#method-first collect([1, 2, 3, 4])->first(function ($value, $key) { return $value == 2; });

                    – Shiro
                    Dec 12 '17 at 15:25






                  • 2





                    You can do same thing with where function. $desired_object = $food->where('id', 24)->first();

                    – Bhavin Thummar
                    Aug 28 '18 at 11:02
















                  83














                  You can use filter, like so:



                  $desired_object = $food->filter(function($item) {
                  return $item->id == 24;
                  })->first();


                  filter will also return a Collection, but since you know there will be only one, you can call first on that Collection.



                  You don't need the filter anymore (or maybe ever, I don't know this is almost 4 years old). You can just use first:



                  $desired_object = $food->first(function($item) {
                  return $item->id == 24;
                  });





                  share|improve this answer





















                  • 7





                    Hey, thanks! I think I can live with that. Still unusually verbose in my opinion for what is usually such an 'Eloquent' framework haha. But it's still much cleaner than the alternatives so far, so I'll take it.

                    – Leng
                    Jan 5 '14 at 7:09













                  • As @squaretastic is pointing out in the other answer, inside your closure you're making an assignement and not a comparison (i.e. you should == and not = )

                    – St0rM
                    Jun 9 '14 at 12:57






                  • 22





                    Actually it's not even necessary to call filter()->first() you can just call first(function(...))

                    – lukasgeiter
                    Feb 4 '15 at 20:10











                  • from Laravel Collection documentation. laravel.com/docs/5.5/collections#method-first collect([1, 2, 3, 4])->first(function ($value, $key) { return $value == 2; });

                    – Shiro
                    Dec 12 '17 at 15:25






                  • 2





                    You can do same thing with where function. $desired_object = $food->where('id', 24)->first();

                    – Bhavin Thummar
                    Aug 28 '18 at 11:02














                  83












                  83








                  83







                  You can use filter, like so:



                  $desired_object = $food->filter(function($item) {
                  return $item->id == 24;
                  })->first();


                  filter will also return a Collection, but since you know there will be only one, you can call first on that Collection.



                  You don't need the filter anymore (or maybe ever, I don't know this is almost 4 years old). You can just use first:



                  $desired_object = $food->first(function($item) {
                  return $item->id == 24;
                  });





                  share|improve this answer















                  You can use filter, like so:



                  $desired_object = $food->filter(function($item) {
                  return $item->id == 24;
                  })->first();


                  filter will also return a Collection, but since you know there will be only one, you can call first on that Collection.



                  You don't need the filter anymore (or maybe ever, I don't know this is almost 4 years old). You can just use first:



                  $desired_object = $food->first(function($item) {
                  return $item->id == 24;
                  });






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Dec 12 '17 at 15:58

























                  answered Jan 5 '14 at 7:04









                  kalleykalley

                  13.4k12933




                  13.4k12933








                  • 7





                    Hey, thanks! I think I can live with that. Still unusually verbose in my opinion for what is usually such an 'Eloquent' framework haha. But it's still much cleaner than the alternatives so far, so I'll take it.

                    – Leng
                    Jan 5 '14 at 7:09













                  • As @squaretastic is pointing out in the other answer, inside your closure you're making an assignement and not a comparison (i.e. you should == and not = )

                    – St0rM
                    Jun 9 '14 at 12:57






                  • 22





                    Actually it's not even necessary to call filter()->first() you can just call first(function(...))

                    – lukasgeiter
                    Feb 4 '15 at 20:10











                  • from Laravel Collection documentation. laravel.com/docs/5.5/collections#method-first collect([1, 2, 3, 4])->first(function ($value, $key) { return $value == 2; });

                    – Shiro
                    Dec 12 '17 at 15:25






                  • 2





                    You can do same thing with where function. $desired_object = $food->where('id', 24)->first();

                    – Bhavin Thummar
                    Aug 28 '18 at 11:02














                  • 7





                    Hey, thanks! I think I can live with that. Still unusually verbose in my opinion for what is usually such an 'Eloquent' framework haha. But it's still much cleaner than the alternatives so far, so I'll take it.

                    – Leng
                    Jan 5 '14 at 7:09













                  • As @squaretastic is pointing out in the other answer, inside your closure you're making an assignement and not a comparison (i.e. you should == and not = )

                    – St0rM
                    Jun 9 '14 at 12:57






                  • 22





                    Actually it's not even necessary to call filter()->first() you can just call first(function(...))

                    – lukasgeiter
                    Feb 4 '15 at 20:10











                  • from Laravel Collection documentation. laravel.com/docs/5.5/collections#method-first collect([1, 2, 3, 4])->first(function ($value, $key) { return $value == 2; });

                    – Shiro
                    Dec 12 '17 at 15:25






                  • 2





                    You can do same thing with where function. $desired_object = $food->where('id', 24)->first();

                    – Bhavin Thummar
                    Aug 28 '18 at 11:02








                  7




                  7





                  Hey, thanks! I think I can live with that. Still unusually verbose in my opinion for what is usually such an 'Eloquent' framework haha. But it's still much cleaner than the alternatives so far, so I'll take it.

                  – Leng
                  Jan 5 '14 at 7:09







                  Hey, thanks! I think I can live with that. Still unusually verbose in my opinion for what is usually such an 'Eloquent' framework haha. But it's still much cleaner than the alternatives so far, so I'll take it.

                  – Leng
                  Jan 5 '14 at 7:09















                  As @squaretastic is pointing out in the other answer, inside your closure you're making an assignement and not a comparison (i.e. you should == and not = )

                  – St0rM
                  Jun 9 '14 at 12:57





                  As @squaretastic is pointing out in the other answer, inside your closure you're making an assignement and not a comparison (i.e. you should == and not = )

                  – St0rM
                  Jun 9 '14 at 12:57




                  22




                  22





                  Actually it's not even necessary to call filter()->first() you can just call first(function(...))

                  – lukasgeiter
                  Feb 4 '15 at 20:10





                  Actually it's not even necessary to call filter()->first() you can just call first(function(...))

                  – lukasgeiter
                  Feb 4 '15 at 20:10













                  from Laravel Collection documentation. laravel.com/docs/5.5/collections#method-first collect([1, 2, 3, 4])->first(function ($value, $key) { return $value == 2; });

                  – Shiro
                  Dec 12 '17 at 15:25





                  from Laravel Collection documentation. laravel.com/docs/5.5/collections#method-first collect([1, 2, 3, 4])->first(function ($value, $key) { return $value == 2; });

                  – Shiro
                  Dec 12 '17 at 15:25




                  2




                  2





                  You can do same thing with where function. $desired_object = $food->where('id', 24)->first();

                  – Bhavin Thummar
                  Aug 28 '18 at 11:02





                  You can do same thing with where function. $desired_object = $food->where('id', 24)->first();

                  – Bhavin Thummar
                  Aug 28 '18 at 11:02













                  86














                  Laravel provides a method called keyBy which allows to set keys by given key in model.



                  $collection = $collection->keyBy('id');



                  will return the collection but with keys being the values of id attribute from any model.



                  Then you can say:



                  $desired_food = $foods->get(21); // Grab the food with an ID of 21



                  and it will grab the correct item without the mess of using a filter function.






                  share|improve this answer





















                  • 2





                    Really useful, especially for performance, ->first() can be slow when called multiple times (foreach in foreach...) so you can "index" your collection like : $exceptions->keyBy(function ($exception) { return $exception->category_id . ' ' . $exception->manufacturer_id; and use ->get($category->id . ' ' . $manufacturer->id) after !

                    – François Breton
                    Apr 25 '16 at 16:32













                  • Does this key continue to be used when new items are added to the collection? Or do I need to use keyBy() every time a new object or array is pushed onto the collection?

                    – Jason
                    Sep 22 '16 at 14:22











                  • Most likely you have to call it again since keyBy returns new collection from what I remember, not sure though, you can check Illuminate/Support/Collection to find it out. (Not working in Laravel for quite some time so someone can correct me).

                    – Maksym Cierzniak
                    Dec 4 '16 at 20:44











                  • This didn't worked for me, it returned another item, the next item, if I type get(1) it will return the item which has number 2 as id.

                    – Jaqueline Passos
                    Jan 21 '17 at 16:42


















                  86














                  Laravel provides a method called keyBy which allows to set keys by given key in model.



                  $collection = $collection->keyBy('id');



                  will return the collection but with keys being the values of id attribute from any model.



                  Then you can say:



                  $desired_food = $foods->get(21); // Grab the food with an ID of 21



                  and it will grab the correct item without the mess of using a filter function.






                  share|improve this answer





















                  • 2





                    Really useful, especially for performance, ->first() can be slow when called multiple times (foreach in foreach...) so you can "index" your collection like : $exceptions->keyBy(function ($exception) { return $exception->category_id . ' ' . $exception->manufacturer_id; and use ->get($category->id . ' ' . $manufacturer->id) after !

                    – François Breton
                    Apr 25 '16 at 16:32













                  • Does this key continue to be used when new items are added to the collection? Or do I need to use keyBy() every time a new object or array is pushed onto the collection?

                    – Jason
                    Sep 22 '16 at 14:22











                  • Most likely you have to call it again since keyBy returns new collection from what I remember, not sure though, you can check Illuminate/Support/Collection to find it out. (Not working in Laravel for quite some time so someone can correct me).

                    – Maksym Cierzniak
                    Dec 4 '16 at 20:44











                  • This didn't worked for me, it returned another item, the next item, if I type get(1) it will return the item which has number 2 as id.

                    – Jaqueline Passos
                    Jan 21 '17 at 16:42
















                  86












                  86








                  86







                  Laravel provides a method called keyBy which allows to set keys by given key in model.



                  $collection = $collection->keyBy('id');



                  will return the collection but with keys being the values of id attribute from any model.



                  Then you can say:



                  $desired_food = $foods->get(21); // Grab the food with an ID of 21



                  and it will grab the correct item without the mess of using a filter function.






                  share|improve this answer















                  Laravel provides a method called keyBy which allows to set keys by given key in model.



                  $collection = $collection->keyBy('id');



                  will return the collection but with keys being the values of id attribute from any model.



                  Then you can say:



                  $desired_food = $foods->get(21); // Grab the food with an ID of 21



                  and it will grab the correct item without the mess of using a filter function.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jun 23 '15 at 19:50









                  ryanhightower

                  337




                  337










                  answered Mar 9 '15 at 9:55









                  Maksym CierzniakMaksym Cierzniak

                  1,82421523




                  1,82421523








                  • 2





                    Really useful, especially for performance, ->first() can be slow when called multiple times (foreach in foreach...) so you can "index" your collection like : $exceptions->keyBy(function ($exception) { return $exception->category_id . ' ' . $exception->manufacturer_id; and use ->get($category->id . ' ' . $manufacturer->id) after !

                    – François Breton
                    Apr 25 '16 at 16:32













                  • Does this key continue to be used when new items are added to the collection? Or do I need to use keyBy() every time a new object or array is pushed onto the collection?

                    – Jason
                    Sep 22 '16 at 14:22











                  • Most likely you have to call it again since keyBy returns new collection from what I remember, not sure though, you can check Illuminate/Support/Collection to find it out. (Not working in Laravel for quite some time so someone can correct me).

                    – Maksym Cierzniak
                    Dec 4 '16 at 20:44











                  • This didn't worked for me, it returned another item, the next item, if I type get(1) it will return the item which has number 2 as id.

                    – Jaqueline Passos
                    Jan 21 '17 at 16:42
















                  • 2





                    Really useful, especially for performance, ->first() can be slow when called multiple times (foreach in foreach...) so you can "index" your collection like : $exceptions->keyBy(function ($exception) { return $exception->category_id . ' ' . $exception->manufacturer_id; and use ->get($category->id . ' ' . $manufacturer->id) after !

                    – François Breton
                    Apr 25 '16 at 16:32













                  • Does this key continue to be used when new items are added to the collection? Or do I need to use keyBy() every time a new object or array is pushed onto the collection?

                    – Jason
                    Sep 22 '16 at 14:22











                  • Most likely you have to call it again since keyBy returns new collection from what I remember, not sure though, you can check Illuminate/Support/Collection to find it out. (Not working in Laravel for quite some time so someone can correct me).

                    – Maksym Cierzniak
                    Dec 4 '16 at 20:44











                  • This didn't worked for me, it returned another item, the next item, if I type get(1) it will return the item which has number 2 as id.

                    – Jaqueline Passos
                    Jan 21 '17 at 16:42










                  2




                  2





                  Really useful, especially for performance, ->first() can be slow when called multiple times (foreach in foreach...) so you can "index" your collection like : $exceptions->keyBy(function ($exception) { return $exception->category_id . ' ' . $exception->manufacturer_id; and use ->get($category->id . ' ' . $manufacturer->id) after !

                  – François Breton
                  Apr 25 '16 at 16:32







                  Really useful, especially for performance, ->first() can be slow when called multiple times (foreach in foreach...) so you can "index" your collection like : $exceptions->keyBy(function ($exception) { return $exception->category_id . ' ' . $exception->manufacturer_id; and use ->get($category->id . ' ' . $manufacturer->id) after !

                  – François Breton
                  Apr 25 '16 at 16:32















                  Does this key continue to be used when new items are added to the collection? Or do I need to use keyBy() every time a new object or array is pushed onto the collection?

                  – Jason
                  Sep 22 '16 at 14:22





                  Does this key continue to be used when new items are added to the collection? Or do I need to use keyBy() every time a new object or array is pushed onto the collection?

                  – Jason
                  Sep 22 '16 at 14:22













                  Most likely you have to call it again since keyBy returns new collection from what I remember, not sure though, you can check Illuminate/Support/Collection to find it out. (Not working in Laravel for quite some time so someone can correct me).

                  – Maksym Cierzniak
                  Dec 4 '16 at 20:44





                  Most likely you have to call it again since keyBy returns new collection from what I remember, not sure though, you can check Illuminate/Support/Collection to find it out. (Not working in Laravel for quite some time so someone can correct me).

                  – Maksym Cierzniak
                  Dec 4 '16 at 20:44













                  This didn't worked for me, it returned another item, the next item, if I type get(1) it will return the item which has number 2 as id.

                  – Jaqueline Passos
                  Jan 21 '17 at 16:42







                  This didn't worked for me, it returned another item, the next item, if I type get(1) it will return the item which has number 2 as id.

                  – Jaqueline Passos
                  Jan 21 '17 at 16:42













                  7














                  Since I don't need to loop entire collection, I think it is better to have helper function like this



                  /**
                  * Check if there is a item in a collection by given key and value
                  * @param IlluminateSupportCollection $collection collection in which search is to be made
                  * @param string $key name of key to be checked
                  * @param string $value value of key to be checkied
                  * @return boolean|object false if not found, object if it is found
                  */
                  function findInCollection(IlluminateSupportCollection $collection, $key, $value) {
                  foreach ($collection as $item) {
                  if (isset($item->$key) && $item->$key == $value) {
                  return $item;
                  }
                  }
                  return FALSE;
                  }





                  share|improve this answer




























                    7














                    Since I don't need to loop entire collection, I think it is better to have helper function like this



                    /**
                    * Check if there is a item in a collection by given key and value
                    * @param IlluminateSupportCollection $collection collection in which search is to be made
                    * @param string $key name of key to be checked
                    * @param string $value value of key to be checkied
                    * @return boolean|object false if not found, object if it is found
                    */
                    function findInCollection(IlluminateSupportCollection $collection, $key, $value) {
                    foreach ($collection as $item) {
                    if (isset($item->$key) && $item->$key == $value) {
                    return $item;
                    }
                    }
                    return FALSE;
                    }





                    share|improve this answer


























                      7












                      7








                      7







                      Since I don't need to loop entire collection, I think it is better to have helper function like this



                      /**
                      * Check if there is a item in a collection by given key and value
                      * @param IlluminateSupportCollection $collection collection in which search is to be made
                      * @param string $key name of key to be checked
                      * @param string $value value of key to be checkied
                      * @return boolean|object false if not found, object if it is found
                      */
                      function findInCollection(IlluminateSupportCollection $collection, $key, $value) {
                      foreach ($collection as $item) {
                      if (isset($item->$key) && $item->$key == $value) {
                      return $item;
                      }
                      }
                      return FALSE;
                      }





                      share|improve this answer













                      Since I don't need to loop entire collection, I think it is better to have helper function like this



                      /**
                      * Check if there is a item in a collection by given key and value
                      * @param IlluminateSupportCollection $collection collection in which search is to be made
                      * @param string $key name of key to be checked
                      * @param string $value value of key to be checkied
                      * @return boolean|object false if not found, object if it is found
                      */
                      function findInCollection(IlluminateSupportCollection $collection, $key, $value) {
                      foreach ($collection as $item) {
                      if (isset($item->$key) && $item->$key == $value) {
                      return $item;
                      }
                      }
                      return FALSE;
                      }






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Aug 14 '14 at 6:48









                      Rohith RaveendranRohith Raveendran

                      2721413




                      2721413























                          5














                          Use the built in collection methods contain and find, which will search by primary ids (instead of array keys). Example:



                          if ($model->collection->contains($primaryId)) {
                          var_dump($model->collection->find($primaryId);
                          }


                          contains() actually just calls find() and checks for null, so you could shorten it down to:



                          if ($myModel = $model->collection->find($primaryId)) {
                          var_dump($myModel);
                          }





                          share|improve this answer
























                          • We understand that find() accepts a primary ID. What we want is a method that accepts any attribute, such as "color" or "age". So far, kalley's method is the only one that works for any attribute.

                            – Leng
                            Jan 13 '15 at 1:08
















                          5














                          Use the built in collection methods contain and find, which will search by primary ids (instead of array keys). Example:



                          if ($model->collection->contains($primaryId)) {
                          var_dump($model->collection->find($primaryId);
                          }


                          contains() actually just calls find() and checks for null, so you could shorten it down to:



                          if ($myModel = $model->collection->find($primaryId)) {
                          var_dump($myModel);
                          }





                          share|improve this answer
























                          • We understand that find() accepts a primary ID. What we want is a method that accepts any attribute, such as "color" or "age". So far, kalley's method is the only one that works for any attribute.

                            – Leng
                            Jan 13 '15 at 1:08














                          5












                          5








                          5







                          Use the built in collection methods contain and find, which will search by primary ids (instead of array keys). Example:



                          if ($model->collection->contains($primaryId)) {
                          var_dump($model->collection->find($primaryId);
                          }


                          contains() actually just calls find() and checks for null, so you could shorten it down to:



                          if ($myModel = $model->collection->find($primaryId)) {
                          var_dump($myModel);
                          }





                          share|improve this answer













                          Use the built in collection methods contain and find, which will search by primary ids (instead of array keys). Example:



                          if ($model->collection->contains($primaryId)) {
                          var_dump($model->collection->find($primaryId);
                          }


                          contains() actually just calls find() and checks for null, so you could shorten it down to:



                          if ($myModel = $model->collection->find($primaryId)) {
                          var_dump($myModel);
                          }






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jan 12 '15 at 21:56









                          Ziad HilalZiad Hilal

                          16625




                          16625













                          • We understand that find() accepts a primary ID. What we want is a method that accepts any attribute, such as "color" or "age". So far, kalley's method is the only one that works for any attribute.

                            – Leng
                            Jan 13 '15 at 1:08



















                          • We understand that find() accepts a primary ID. What we want is a method that accepts any attribute, such as "color" or "age". So far, kalley's method is the only one that works for any attribute.

                            – Leng
                            Jan 13 '15 at 1:08

















                          We understand that find() accepts a primary ID. What we want is a method that accepts any attribute, such as "color" or "age". So far, kalley's method is the only one that works for any attribute.

                          – Leng
                          Jan 13 '15 at 1:08





                          We understand that find() accepts a primary ID. What we want is a method that accepts any attribute, such as "color" or "age". So far, kalley's method is the only one that works for any attribute.

                          – Leng
                          Jan 13 '15 at 1:08











                          5














                          I know this question was originally asked before Laravel 5.0 was released, but as of Laravel 5.0, Collections support the where() method for this purpose.



                          For Laravel 5.0, 5.1, and 5.2, the where() method on the Collection will only do an equals comparison. Also, it does a strict equals comparison (===) by default. To do a loose comparison (==), you can either pass false as the third parameter or use the whereLoose() method.



                          As of Laravel 5.3, the where() method was expanded to work more like the where() method for the query builder, which accepts an operator as the second parameter. Also like the query builder, the operator will default to an equals comparison if none is supplied. The default comparison was also switched from strict by default to loose by default. So, if you'd like a strict comparison, you can use whereStrict(), or just use === as the operator for where().



                          Therefore, as of Laravel 5.0, the last code example in the question will work exactly as intended:



                          $foods = Food::all();
                          $green_foods = $foods->where('color', 'green'); // This will work. :)

                          // This will only work in Laravel 5.3+
                          $cheap_foods = $foods->where('price', '<', 5);

                          // Assuming "quantity" is an integer...
                          // This will not match any records in 5.0, 5.1, 5.2 due to the default strict comparison.
                          // This will match records just fine in 5.3+ due to the default loose comparison.
                          $dozen_foods = $foods->where('quantity', '12');





                          share|improve this answer




























                            5














                            I know this question was originally asked before Laravel 5.0 was released, but as of Laravel 5.0, Collections support the where() method for this purpose.



                            For Laravel 5.0, 5.1, and 5.2, the where() method on the Collection will only do an equals comparison. Also, it does a strict equals comparison (===) by default. To do a loose comparison (==), you can either pass false as the third parameter or use the whereLoose() method.



                            As of Laravel 5.3, the where() method was expanded to work more like the where() method for the query builder, which accepts an operator as the second parameter. Also like the query builder, the operator will default to an equals comparison if none is supplied. The default comparison was also switched from strict by default to loose by default. So, if you'd like a strict comparison, you can use whereStrict(), or just use === as the operator for where().



                            Therefore, as of Laravel 5.0, the last code example in the question will work exactly as intended:



                            $foods = Food::all();
                            $green_foods = $foods->where('color', 'green'); // This will work. :)

                            // This will only work in Laravel 5.3+
                            $cheap_foods = $foods->where('price', '<', 5);

                            // Assuming "quantity" is an integer...
                            // This will not match any records in 5.0, 5.1, 5.2 due to the default strict comparison.
                            // This will match records just fine in 5.3+ due to the default loose comparison.
                            $dozen_foods = $foods->where('quantity', '12');





                            share|improve this answer


























                              5












                              5








                              5







                              I know this question was originally asked before Laravel 5.0 was released, but as of Laravel 5.0, Collections support the where() method for this purpose.



                              For Laravel 5.0, 5.1, and 5.2, the where() method on the Collection will only do an equals comparison. Also, it does a strict equals comparison (===) by default. To do a loose comparison (==), you can either pass false as the third parameter or use the whereLoose() method.



                              As of Laravel 5.3, the where() method was expanded to work more like the where() method for the query builder, which accepts an operator as the second parameter. Also like the query builder, the operator will default to an equals comparison if none is supplied. The default comparison was also switched from strict by default to loose by default. So, if you'd like a strict comparison, you can use whereStrict(), or just use === as the operator for where().



                              Therefore, as of Laravel 5.0, the last code example in the question will work exactly as intended:



                              $foods = Food::all();
                              $green_foods = $foods->where('color', 'green'); // This will work. :)

                              // This will only work in Laravel 5.3+
                              $cheap_foods = $foods->where('price', '<', 5);

                              // Assuming "quantity" is an integer...
                              // This will not match any records in 5.0, 5.1, 5.2 due to the default strict comparison.
                              // This will match records just fine in 5.3+ due to the default loose comparison.
                              $dozen_foods = $foods->where('quantity', '12');





                              share|improve this answer













                              I know this question was originally asked before Laravel 5.0 was released, but as of Laravel 5.0, Collections support the where() method for this purpose.



                              For Laravel 5.0, 5.1, and 5.2, the where() method on the Collection will only do an equals comparison. Also, it does a strict equals comparison (===) by default. To do a loose comparison (==), you can either pass false as the third parameter or use the whereLoose() method.



                              As of Laravel 5.3, the where() method was expanded to work more like the where() method for the query builder, which accepts an operator as the second parameter. Also like the query builder, the operator will default to an equals comparison if none is supplied. The default comparison was also switched from strict by default to loose by default. So, if you'd like a strict comparison, you can use whereStrict(), or just use === as the operator for where().



                              Therefore, as of Laravel 5.0, the last code example in the question will work exactly as intended:



                              $foods = Food::all();
                              $green_foods = $foods->where('color', 'green'); // This will work. :)

                              // This will only work in Laravel 5.3+
                              $cheap_foods = $foods->where('price', '<', 5);

                              // Assuming "quantity" is an integer...
                              // This will not match any records in 5.0, 5.1, 5.2 due to the default strict comparison.
                              // This will match records just fine in 5.3+ due to the default loose comparison.
                              $dozen_foods = $foods->where('quantity', '12');






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jun 3 '17 at 2:27









                              patricuspatricus

                              32.5k66682




                              32.5k66682























                                  3














                                  I have to point out that there is a small but absolutely CRITICAL error in kalley's answer. I struggled with this for several hours before realizing:



                                  Inside the function, what you are returning is a comparison, and thus something like this would be more correct:



                                  $desired_object = $food->filter(function($item) {
                                  return ($item->id **==** 24);
                                  })->first();





                                  share|improve this answer



















                                  • 1





                                    Yes, thanks for pointing this out. It's also important to note that the filter function is no different from my foreach() example performance-wise, because it just does the same kind of loop... in fact, my foreach() example is better performing because it breaks upon finding the correct model. Also... {Collection}->find(24) will grab by primary key, which makes it the best option here. The filter Kalley proposed is actually identical to $desired_object = $foods->find(24);.

                                    – Leng
                                    May 16 '14 at 4:38








                                  • 1





                                    Never seen the **==** operator, what does it do?

                                    – kiradotee
                                    Jun 1 '17 at 12:42











                                  • @kiradotee I think the OP was just attempting to emphasize the double equal comparison operator (==). The original answer only used one equal sign, so it was doing an assignment instead of comparison. OP was trying to emphasize there should be two equal signs.

                                    – patricus
                                    Jun 3 '17 at 2:01


















                                  3














                                  I have to point out that there is a small but absolutely CRITICAL error in kalley's answer. I struggled with this for several hours before realizing:



                                  Inside the function, what you are returning is a comparison, and thus something like this would be more correct:



                                  $desired_object = $food->filter(function($item) {
                                  return ($item->id **==** 24);
                                  })->first();





                                  share|improve this answer



















                                  • 1





                                    Yes, thanks for pointing this out. It's also important to note that the filter function is no different from my foreach() example performance-wise, because it just does the same kind of loop... in fact, my foreach() example is better performing because it breaks upon finding the correct model. Also... {Collection}->find(24) will grab by primary key, which makes it the best option here. The filter Kalley proposed is actually identical to $desired_object = $foods->find(24);.

                                    – Leng
                                    May 16 '14 at 4:38








                                  • 1





                                    Never seen the **==** operator, what does it do?

                                    – kiradotee
                                    Jun 1 '17 at 12:42











                                  • @kiradotee I think the OP was just attempting to emphasize the double equal comparison operator (==). The original answer only used one equal sign, so it was doing an assignment instead of comparison. OP was trying to emphasize there should be two equal signs.

                                    – patricus
                                    Jun 3 '17 at 2:01
















                                  3












                                  3








                                  3







                                  I have to point out that there is a small but absolutely CRITICAL error in kalley's answer. I struggled with this for several hours before realizing:



                                  Inside the function, what you are returning is a comparison, and thus something like this would be more correct:



                                  $desired_object = $food->filter(function($item) {
                                  return ($item->id **==** 24);
                                  })->first();





                                  share|improve this answer













                                  I have to point out that there is a small but absolutely CRITICAL error in kalley's answer. I struggled with this for several hours before realizing:



                                  Inside the function, what you are returning is a comparison, and thus something like this would be more correct:



                                  $desired_object = $food->filter(function($item) {
                                  return ($item->id **==** 24);
                                  })->first();






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered May 15 '14 at 23:29









                                  squaretasticsquaretastic

                                  8010




                                  8010








                                  • 1





                                    Yes, thanks for pointing this out. It's also important to note that the filter function is no different from my foreach() example performance-wise, because it just does the same kind of loop... in fact, my foreach() example is better performing because it breaks upon finding the correct model. Also... {Collection}->find(24) will grab by primary key, which makes it the best option here. The filter Kalley proposed is actually identical to $desired_object = $foods->find(24);.

                                    – Leng
                                    May 16 '14 at 4:38








                                  • 1





                                    Never seen the **==** operator, what does it do?

                                    – kiradotee
                                    Jun 1 '17 at 12:42











                                  • @kiradotee I think the OP was just attempting to emphasize the double equal comparison operator (==). The original answer only used one equal sign, so it was doing an assignment instead of comparison. OP was trying to emphasize there should be two equal signs.

                                    – patricus
                                    Jun 3 '17 at 2:01
















                                  • 1





                                    Yes, thanks for pointing this out. It's also important to note that the filter function is no different from my foreach() example performance-wise, because it just does the same kind of loop... in fact, my foreach() example is better performing because it breaks upon finding the correct model. Also... {Collection}->find(24) will grab by primary key, which makes it the best option here. The filter Kalley proposed is actually identical to $desired_object = $foods->find(24);.

                                    – Leng
                                    May 16 '14 at 4:38








                                  • 1





                                    Never seen the **==** operator, what does it do?

                                    – kiradotee
                                    Jun 1 '17 at 12:42











                                  • @kiradotee I think the OP was just attempting to emphasize the double equal comparison operator (==). The original answer only used one equal sign, so it was doing an assignment instead of comparison. OP was trying to emphasize there should be two equal signs.

                                    – patricus
                                    Jun 3 '17 at 2:01










                                  1




                                  1





                                  Yes, thanks for pointing this out. It's also important to note that the filter function is no different from my foreach() example performance-wise, because it just does the same kind of loop... in fact, my foreach() example is better performing because it breaks upon finding the correct model. Also... {Collection}->find(24) will grab by primary key, which makes it the best option here. The filter Kalley proposed is actually identical to $desired_object = $foods->find(24);.

                                  – Leng
                                  May 16 '14 at 4:38







                                  Yes, thanks for pointing this out. It's also important to note that the filter function is no different from my foreach() example performance-wise, because it just does the same kind of loop... in fact, my foreach() example is better performing because it breaks upon finding the correct model. Also... {Collection}->find(24) will grab by primary key, which makes it the best option here. The filter Kalley proposed is actually identical to $desired_object = $foods->find(24);.

                                  – Leng
                                  May 16 '14 at 4:38






                                  1




                                  1





                                  Never seen the **==** operator, what does it do?

                                  – kiradotee
                                  Jun 1 '17 at 12:42





                                  Never seen the **==** operator, what does it do?

                                  – kiradotee
                                  Jun 1 '17 at 12:42













                                  @kiradotee I think the OP was just attempting to emphasize the double equal comparison operator (==). The original answer only used one equal sign, so it was doing an assignment instead of comparison. OP was trying to emphasize there should be two equal signs.

                                  – patricus
                                  Jun 3 '17 at 2:01







                                  @kiradotee I think the OP was just attempting to emphasize the double equal comparison operator (==). The original answer only used one equal sign, so it was doing an assignment instead of comparison. OP was trying to emphasize there should be two equal signs.

                                  – patricus
                                  Jun 3 '17 at 2:01













                                  3














                                  As from Laravel 5.5 you can use firstWhere()



                                  In you case:



                                  $green_foods = $foods->firstWhere('color', 'green');





                                  share|improve this answer



















                                  • 1





                                    This should be the accepted answer after Laravel 5.5

                                    – beerwin
                                    Mar 13 at 16:13
















                                  3














                                  As from Laravel 5.5 you can use firstWhere()



                                  In you case:



                                  $green_foods = $foods->firstWhere('color', 'green');





                                  share|improve this answer



















                                  • 1





                                    This should be the accepted answer after Laravel 5.5

                                    – beerwin
                                    Mar 13 at 16:13














                                  3












                                  3








                                  3







                                  As from Laravel 5.5 you can use firstWhere()



                                  In you case:



                                  $green_foods = $foods->firstWhere('color', 'green');





                                  share|improve this answer













                                  As from Laravel 5.5 you can use firstWhere()



                                  In you case:



                                  $green_foods = $foods->firstWhere('color', 'green');






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Nov 23 '18 at 13:33









                                  Victor TimoftiiVictor Timoftii

                                  45147




                                  45147








                                  • 1





                                    This should be the accepted answer after Laravel 5.5

                                    – beerwin
                                    Mar 13 at 16:13














                                  • 1





                                    This should be the accepted answer after Laravel 5.5

                                    – beerwin
                                    Mar 13 at 16:13








                                  1




                                  1





                                  This should be the accepted answer after Laravel 5.5

                                  – beerwin
                                  Mar 13 at 16:13





                                  This should be the accepted answer after Laravel 5.5

                                  – beerwin
                                  Mar 13 at 16:13











                                  1














                                  Elegant solution for finding a value (http://betamode.de/2013/10/17/laravel-4-eloquent-check-if-there-is-a-model-with-certain-key-value-pair-in-a-collection/) can be adapted:



                                  $desired_object_key = $food->array_search(24, $food->lists('id'));
                                  if ($desired_object_key !== false) {
                                  $desired_object = $food[$desired_object_key];
                                  }





                                  share|improve this answer




























                                    1














                                    Elegant solution for finding a value (http://betamode.de/2013/10/17/laravel-4-eloquent-check-if-there-is-a-model-with-certain-key-value-pair-in-a-collection/) can be adapted:



                                    $desired_object_key = $food->array_search(24, $food->lists('id'));
                                    if ($desired_object_key !== false) {
                                    $desired_object = $food[$desired_object_key];
                                    }





                                    share|improve this answer


























                                      1












                                      1








                                      1







                                      Elegant solution for finding a value (http://betamode.de/2013/10/17/laravel-4-eloquent-check-if-there-is-a-model-with-certain-key-value-pair-in-a-collection/) can be adapted:



                                      $desired_object_key = $food->array_search(24, $food->lists('id'));
                                      if ($desired_object_key !== false) {
                                      $desired_object = $food[$desired_object_key];
                                      }





                                      share|improve this answer













                                      Elegant solution for finding a value (http://betamode.de/2013/10/17/laravel-4-eloquent-check-if-there-is-a-model-with-certain-key-value-pair-in-a-collection/) can be adapted:



                                      $desired_object_key = $food->array_search(24, $food->lists('id'));
                                      if ($desired_object_key !== false) {
                                      $desired_object = $food[$desired_object_key];
                                      }






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Sep 30 '14 at 10:19









                                      softfrogsoftfrog

                                      357




                                      357























                                          0














                                          As the question above when you are using the where clause you also need to use the get Or first method to get the result.



                                          /**
                                          *Get all food
                                          *
                                          */

                                          $foods = Food::all();

                                          /**
                                          *Get green food
                                          *
                                          */

                                          $green_foods = Food::where('color', 'green')->get();





                                          share|improve this answer




























                                            0














                                            As the question above when you are using the where clause you also need to use the get Or first method to get the result.



                                            /**
                                            *Get all food
                                            *
                                            */

                                            $foods = Food::all();

                                            /**
                                            *Get green food
                                            *
                                            */

                                            $green_foods = Food::where('color', 'green')->get();





                                            share|improve this answer


























                                              0












                                              0








                                              0







                                              As the question above when you are using the where clause you also need to use the get Or first method to get the result.



                                              /**
                                              *Get all food
                                              *
                                              */

                                              $foods = Food::all();

                                              /**
                                              *Get green food
                                              *
                                              */

                                              $green_foods = Food::where('color', 'green')->get();





                                              share|improve this answer













                                              As the question above when you are using the where clause you also need to use the get Or first method to get the result.



                                              /**
                                              *Get all food
                                              *
                                              */

                                              $foods = Food::all();

                                              /**
                                              *Get green food
                                              *
                                              */

                                              $green_foods = Food::where('color', 'green')->get();






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Oct 18 '17 at 8:35









                                              MarcoMarco

                                              1891114




                                              1891114






























                                                  draft saved

                                                  draft discarded




















































                                                  Thanks for contributing an answer to Stack Overflow!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid



                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function () {
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f20931020%2flaravel-get-object-from-collection-by-attribute%23new-answer', 'question_page');
                                                  }
                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  這個網誌中的熱門文章

                                                  Tangent Lines Diagram Along Smooth Curve

                                                  Yusuf al-Mu'taman ibn Hud

                                                  Zucchini