ItSolutionStuff.com

Get Array of Ids from Eloquent Models in Laravel

By Hardik Savani • April 16, 2024
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, laravel 9, laravel 10 and laravel 11 version.

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

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Select Specific Columns in Laravel Eloquent Model?

Read Now →

How to Get All Models in Laravel?

Read Now →

How to Get Columns Names from Model in Laravel?

Read Now →

How to Create Model in Laravel using Command?

Read Now →

Laravel Eloquent Group By Year with Sum Example

Read Now →

Laravel Eloquent Model Custom Function Example

Read Now →

Laravel Replicate Model with Relationships Example

Read Now →

How to use Laravel Model Observers?

Read Now →

Laravel Eloquent updateOrCreate Example

Read Now →

Laravel Eloquent whereNull() Query Example

Read Now →

Laravel Global Scope Tutorial Example

Read Now →

How to Create and Use Query Scope in Laravel Eloquent

Read Now →

Laravel Model Caching - Performance Boost Tutorial

Read Now →

Laravel Join with Subquery in Query Builder Example

Read Now →