Reputation: 10064
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
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
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