How to get IDs from a collection in Laravel

Categorized as Laravel Tagged ,

You can always retrieve IDs from Eloquent Collection in Laravel with the built-in method modelKeys:

// 🤔 Could be this statement
$ids = Category::all()->pluck('id');

// ✅ Could also be this statement
$ids = Category::all()->modelKeys();

dd($ids);

As the official documentation says,

the modelKeys method returns the primary keys for all models in the collection

$users->modelKeys();
 
// [1, 2, 3, 4, 5]

Leave a reply

Your email address will not be published. Required fields are marked *