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