Laravel 4, Eloquent: Check if there is a Model with certain key-value pair in a Collection
Published 2013-10-17, 16:47
I wanted to find out if there already is a Model with a certain value for a certain column in a Collection that I retrieved realier in my code, e.g. is there already a User with name = Müller in my $users Collection?
$users->contains() can only check if there is a model with a certain primary key, and there also is no method to trivially search through all Models. Of course this all could be hacked together somehow*, but after a bit of searching I found this nice way to solve my question:
$value = 'Müller'; $key = 'name'; if(in_array($value, $users->lists($key))) { ... }
Collection->lists() gets an array with all the values of the Model for the requested key. Checking if our new value is in there, is super simple.
*Of course I first tried it this way:
- use $collection->filter() and then count the result
- hack $collection->contains() +$collection->find() to accept a field name as a parameter
- see 2, but copy the methods as private methods to my controller instead of tinkering with the framework code directly
All 3 solutions worked, but needed lots of ugly code.
( 1 )
[…] solution for finding a value (http://betamode.de/2013/10/17/laravel-4-eloquent-check-if-there-is-a-model-with-certain-key-value-pa…😉 can be […]
Pingback von Laravel: Get Object From Collection By Attribute – inneka.com am 5. Februar 2020