Laravel Get Array of Ids from Eloquent Models Example

Dec 07, 2022 . Admin



Hello Friends,

In this post, laravel get array of ids from eloquent models. let’s discuss about laravel get array of ids from eloquent models. This article will give you a simple example of laravel get array of ids from eloquent models. This article goes in detailed on laravel get array of ids from eloquent models.

Sometimes we need to get an array of ids from the table. There are two ways to get an array of ids in laravel. Laravel provides pluck() and modelKeys() eloquent methods to get an array from the collection in laravel. so let's see both example below:

You can use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.

Example 1: using pluck()
app/Http/Controllers/DemoController.php
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
  
class DemoController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $usersIDs = User::pluck('id')->toArray();
  
        dd($usersIDs);
    }
}
Output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 11
    [3] => 12
    [4] => 13
    [5] => 14
    [6] => 15
    [7] => 16
    [8] => 17
    [9] => 18
) 
Example 2: using modelKeys() app/Http/Controllers/DemoController.php
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
  
class DemoController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $usersIDs = User::all()->modelKeys();
  
        dd($usersIDs);
    }
}
Output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 11
    [3] => 12
    [4] => 13
    [5] => 14
    [6] => 15
    [7] => 16
    [8] => 17
    [9] => 18
) 

I hope it can help you...

#Laravel