Navigate back to the homepage

Get Array of IDs from Eloquent Collection in Laravel

Vishnu Damwala
January 2nd, 2020 · 1 min read

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

1$allBooks = Book::pluck('id');
2// returns array of book IDs
With relationship
1$bookIds = $author->books->pluck('id');
2// 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.

1$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.

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

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

More articles from MeshWorld

Write a Program to print Hello, World! in JAVA

A program to print "Hello World!" in JAVA.

January 2nd, 2020 · 1 min read

Write a Program to print Hello, World! in C

A program to print "Hello World!" in C.

January 1st, 2020 · 1 min read
© 2017–2020 MeshWorld
Link to $https://twitter.com/meshworldindiaLink to $https://facebook.com/meshworldindiaLink to $https://instagram.com/meshworld.india/