ryanrca's avatar

How to find an id from data in a collection? Whats the most expressive, succinct way?

Okay, This is something way to common to be struggling with, but for some reason I'm struggling.

Suppose I have a collection of model data:

    [ 
        {"id": 1, "name": "Joe"},
        {"id": 2, "name": "Peg"},
        {"id": 3, "name": "Sam"}
    ]  

What is the simplest, most readable way to find the id for a given name.

I feel like an idiot because all I can come up with are variants of this:

        $users = User::select(['id', 'name'])->get();
        $just_names = $users->pluck('name');

        if ($key = array_search($search4me, $just_names->toArray())) {
            
            // A dumb hack because I suck at collections:
            $key++;   

            $this->id = $key;
       }

There must be lots of better ways, but for some reason I can't seem to come up with one.

0 likes
3 replies
andonovn's avatar

Not sure this is the "simplest, most readable way" but

$key = $users->search(function ($user, $key) use ($search4me) {
    return $user->name === $search4me;
});

$this->id = $users->get($key)->id;

I've just made it up after a quick search at the documentation ( https://laravel.com/docs/5.3/collections#available-methods ). If you are going to use it, make sure you cover the cases where nothing will match your search/key etc. Also note that the search() will return you the first match.

And one note on your code: it assume that your items in the database will always have the correct id order but in real applications that is not the case because imagine you delete some record, or some transaction fail (it will preserve the ids before rollback), etc. What I mean by example: if your collection contains 200 items, they must be with ids of 0-199 or the $key++; part of your code will fail.

SaeedPrez's avatar
Level 50

I would think ->where() is the easiest for this..

// Get a collection with users from database
$users = User::select(['id', 'name'])->get();

// Search that collection for a user with name joe
// and return the first user's id
$id = $users->where('name', 'joe')->first()->id;

https://laravel.com/docs/5.3/collections#method-where

1 like
ryanrca's avatar

I do feel like an idiot, this is a perfect answer.

In my head, I think of "where()" as a eloquent method for SQL. I overlooked the fact it's also a collection operator.

Thanks!

1 like

Please or to participate in this conversation.