Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();

like image 248
kjdion84 Avatar asked Oct 17 '25 11:10

kjdion84


2 Answers

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;
});
like image 57
Alexey Mezenin Avatar answered Oct 19 '25 01:10

Alexey Mezenin


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();

like image 26
mwal Avatar answered Oct 19 '25 01:10

mwal