Laravel 4, Eloquent: Check if there is a Model with certain key-value pair in a Collection

Veröffentlicht am 17.10.2013, 16:47 Uhr

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:

  1. use $collection->filter() and then count the result
  2. hack $collection->contains() +$collection->find() to accept a field name as a parameter
  3. 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.

Diskussion zum Artikel

» Selbst kommentieren

  1. Zum Artikel Laravel 4, Eloquent: Check if there is a Model with certain key-value pair in a Collection sind noch keine Kommentare vorhanden. Deine Meinung wäre jedoch willkommen!

Sorry, the comment form is closed at this time.


Fatal error: Uncaught Error: Call to undefined function wp_ftr_googlestats() in /www/htdocs/w012bf20/betamode.de/wp-content/themes/betamode/footer.php:19 Stack trace: #0 /www/htdocs/w012bf20/betamode.de/wp-includes/template.php(684): require_once() #1 /www/htdocs/w012bf20/betamode.de/wp-includes/template.php(643): load_template('/www/htdocs/w01...', true) #2 /www/htdocs/w012bf20/betamode.de/wp-includes/general-template.php(84): locate_template(Array, true) #3 /www/htdocs/w012bf20/betamode.de/wp-content/themes/betamode/index.php(43): get_footer() #4 /www/htdocs/w012bf20/betamode.de/wp-includes/template-loader.php(74): include('/www/htdocs/w01...') #5 /www/htdocs/w012bf20/betamode.de/wp-blog-header.php(19): require_once('/www/htdocs/w01...') #6 /www/htdocs/w012bf20/betamode.de/index.php(17): require('/www/htdocs/w01...') #7 {main} thrown in /www/htdocs/w012bf20/betamode.de/wp-content/themes/betamode/footer.php on line 19