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, 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Select Specific Columns in Laravel Eloquent Model?
- How to Get All Models in Laravel?
- How to Get Columns Names from Model in Laravel?
- How to Create Model in Laravel using Command?
- Laravel Eloquent Group By Year with Sum Example
- Laravel Eloquent Model Custom Function Example
- Laravel Replicate Model with Relationships Example
- How to use Laravel Model Observers?
- Laravel Eloquent updateOrCreate Example
- Laravel Eloquent whereNull() Query Example
- Laravel Global Scope Tutorial Example
- How to Create and Use Query Scope in Laravel Eloquent
- Laravel Model Caching - Performance Boost Tutorial
- Laravel Join with Subquery in Query Builder Example