kjdion84
kjdion84

Reputation: 10064

Get key from collection item

How do I get the key from a collection item?

$posts= Post::all();

Example (doesn't work):

$key = $posts->where('id', $id)->getKey();

Upvotes: 4

Views: 23223

Answers (2)

mwal
mwal

Reputation: 3133

Try $post_ids = Post::pluck('id');

That grabs just the id column from all the Post records and returns them as a collection.

If you want just a plain array, add toArray():

$post_ids = Post::pluck('id')->toArray();

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

The all() will return a collection without keys. If you're talking about integer keys like 0, 1, 2 etc, use the search() method:

$key = $posts->search(function($i) use($id) {
    return $i->id === $id;
});

Upvotes: 6

Related Questions