Get Array of IDs from Eloquent Collection: pluck() or modelKeys()
Laravel Tips & Tricks #laravel #eloquent #php #collection #pluck #modelKeys

Get Array of IDs from Eloquent Collection: pluck() or modelKeys()

3 min read Mohamed Said Mohamed Said

When working with Laravel Eloquent, a common task is to retrieve a collection of records and then extract just their primary keys into an array. This is particularly useful when dealing with relationships, such as fetching all permission IDs associated with a specific role.

Laravel provides elegant solutions for this, with two primary methods standing out: pluck() and modelKeys().

Using pluck()

The pluck() method is a widely recognized and versatile tool within Laravel collections. It allows you to retrieve a list of values for a specified key from each item in the collection. For instance, if you have a Role model that hasMany Permission models, you can easily get an array of permission IDs like this:

// Assuming $role is an instance of your Role model
$permissionIDs = $role->permissions->pluck('id');

This code snippet iterates through the permissions collection associated with the $role and extracts the value of the id key from each permission model, returning them as a simple PHP array.

The pluck() method is also available directly on the Eloquent Query Builder, allowing you to fetch only the IDs from the database without retrieving the entire model objects:

$allPermissionIDs = Permission::pluck('id');

This approach is highly efficient as it only selects the id column from the database.

Introducing modelKeys()

Laravel also offers a more specialized method called modelKeys(). This method is specifically designed to retrieve an array of the primary keys from an Eloquent Collection. Its official description is concise: "Get the array of primary keys."

Here's how you would use it in the same scenario:

// Assuming $role is an instance of your Role model
$permissionIDs = $role->permissions->modelKeys();

Interestingly, modelKeys() often results in the same character count as pluck('id'), making it a neat alternative. A key distinction is that modelKeys() is a method of the Illuminate\Database\Eloquent\Collection class, not the Eloquent model itself.

This means you cannot directly call modelKeys() on a Query Builder instance:

// This will result in an error:
// "Call to undefined method App\Models\Permission::modelKeys()"
$allPermissions = Permission::modelKeys();

To use modelKeys() when you need all primary keys from a table, you must first retrieve all the models into a collection:

$allPermissions = Permission::all()->modelKeys();

However, be mindful of potential performance implications if you are fetching all records from a very large table. In such cases, using pluck('id') directly on the Query Builder is generally more performant.

When to Use Which?

  • pluck(): Use this method when you need to extract values for a specific key (not necessarily the primary key) from a collection, or when you want to fetch only primary keys directly from the database query builder for efficiency.
  • modelKeys(): Use this method when you already have an Eloquent Collection and want to specifically retrieve an array of its primary keys. It's a clear and semantic way to express your intent.

Both methods are valuable tools in a Laravel developer's arsenal, offering efficient ways to manipulate and extract data from Eloquent collections.

Key Takeaways:

  • pluck('id') is versatile and can be used on Query Builders and Collections to extract values by key.
  • modelKeys() is specifically for Eloquent Collections and retrieves an array of primary keys.
  • For fetching all primary keys from a large table, Permission::pluck('id') is generally more performant than Permission::all()->modelKeys().

Source: Get Array of IDs from Eloquent Collection: pluck() or modelKeys()

Found this useful?

Frequently Asked Questions

3 questions
Q01 What is the difference between `pluck()` and `modelKeys()` in Laravel?
`pluck()` is a more general method that can extract values for any specified key from a collection or directly from a query builder. `modelKeys()` is specifically designed for Eloquent Collections and retrieves an array of their primary keys.
Q02 Can I use `modelKeys()` directly on an Eloquent Query Builder?
No, `modelKeys()` is a method of the `Illuminate\Database\Eloquent\Collection` class. You cannot call it directly on a Query Builder. You must first fetch the results into a collection using methods like `all()` or by accessing a relationship.
Q03 Which method is more performant for getting all IDs from a large table?
For fetching all primary keys from a large table, using `YourModel::pluck('id')` directly on the Query Builder is generally more performant than retrieving all models with `YourModel::all()` and then calling `modelKeys()`.

Continue reading

More Articles

View all