Get Array of Ids from Eloquent Models in Laravel

Hey Developer,

This article will provide some of the most important example laravel eloquent get list of ids. This article will give you a simple example of how to get all ids from table laravel. I explained simply step by step get array of ids laravel. I would like to share with you laravel get array of ids from model.

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 laravel 6, laravel 7, laravel 8 and laravel 9 version.

Example 1: using pluck()

app/Http/Controllers/DemoController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsUser;

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 AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsUser;

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…

1 thought on “Get Array of Ids from Eloquent Models in Laravel”

Leave a Comment