How to Get Array of Ids from Eloquent Models in Laravel?
Teams applying “How to Get Array of Ids from Eloquent Models in Laravel?” in a production project can use mergers and acquisitions to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.
Before copying the example into a live application, confirm version-specific behaviour with the official Laravel website and test it against the project’s actual database and runtime.
Dec 07, 2022
Hello Friends,
In this post, we will learn 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
)
- How to Notifications With database Driver in Laravel 11?
- How to Send Email Via Notification in Laravel 11?
- How to Install and Configure Laravel 11 Debugbar?
- How to Like Dislike System in Laravel 11?
- How to Paginate a Model with Relationship in Laravel 11?
- Laravel 11 Upload Files to Amazon S3 Example
- Laravel 11 Send WhatsApp Messages Example
- Laravel 11 Rest API Authentication Using JWT Tutorial