Get Array of IDs from Eloquent Collection

Updated at 11-Apr-2021, By samar

Get Array of IDs from Eloquent Collection

With this article, we’ll look at some examples of how to address the "Get Array of IDs from Eloquent Collection" problem.

  • Get array of IDs from Eloquent relationships using pluck function

    --PATH app\Http\Controllers\<YourController>.php
    $post = Post::where('id',1)->first();
    $commentIDs = $post->comments->pluck('id');
    //Data in object collection
    print_r($commentIDs);
    //Data in array 
    print_r($commentIDs->toArray());
    

    Sometimes you have to get the Array of IDs from eloquent collection for some records. Imagine, that you have hasMany() relationship – one Post has many Comments. And then you want to get IDs of comments by a certain Post. You can get the IDs of comments of the related post using pluck function. 

    Output

    Data in Collection Object

    Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => 3 [1] => 4 [2] => 5 ) )

    Data in Array

    Array ( [0] => 3 [1] => 4 [2] => 5 )
  • Get array of IDs from Eloquent relationships using modelKeys function

    --PATH app\Http\Controllers\<YourController>.php
    $post = Post::where('id',1)->first();
    $commentIDs = $post->comments->modelKeys();
    print_r($commentIDs);
    $comments = Comment::whereIn('id', $commentIDs)->get();
    

    You can use modelKeys method on eloquent relationship method comments (hasMany) to get the IDs of the comments table records which are related to this particular post. You can also get all the comments using these IDs with whereIn method in laravel. The value of $commentIDs should be in array format. 

    Output
    Array ( [0] => 3 [1] => 4 [2] => 5 )

Back to code snippet queries related laravel