Get Array of IDs from Eloquent Collection in Laravel

A tutorial how to get array of ids from Eloquent Collection in Laravel

The best thing about Laravel’s Eloquent ORM is the ease with which you could perform BREAD(Browse, Read, Edit, Add, Delete) operations on the multiple databases.

Suppose there is a need to get an array of IDs for records in collection/table. Laravel Eloquent provides a simple and easy way to get all IDs.

Two ways to get an array of IDs

  • Using pluck()
  • Using modelKeys()

Example

Assume, that you have hasMany() relationship – one Author can write many Books. And then you need to get IDs of books by a certain author.

Using pluck()

Both Model and Collection supports pluck()

$allBooks = Book::pluck('id');
// returns array of book IDs

With relationship

$bookIds = $author->books->pluck('id');
// returns array of IDs

Using modelKeys()

The modelKeys() function comes handy when the primary key name is other than “id“. This method in Laravel model gives an array of IDs from collection, stated officially on their site.

$bookIds = Book::modelKeys();

Here modelKeys(), will give an undefined error “Call to undefined method App\Book::modelKeys()”

The workaround is by retrieving all records in collection and with the modelKeys() function, primary keys for model can be retrieved in array form.

$allBooks = Book::all()->modelKeys();

Note : You may face performance issues if you’re retrieving all records for table having large number of records

Avatar

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳

Next
Previous

Related