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.

An array of IDs can be obtained in two ways:

  • 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.

Code with pluck() function:

pluck()

The pluck() exists for both Model and Collection

With relationship

modelKeys()

The modelKeys() function returns primary keys for all models in the collection in an array form.

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.

Share your views

LEAVE A REPLY

Please enter your comment!
Please enter your name here